Hooks的出现,想必你们有所了解。若是你是一个Hooks新手,想用Hooks去构造你的应用程序。不要心急,你只须要跟着我一块儿学习hooks,半个小时你就能掌握React Hooks,并用Hooks去重构你的项目html
const [state, setState] = useState(initialState);
复制代码
在初始渲染的时候,返回的状态( state )与做为第一个参数( initialState )传递的值相同。react
setState 函数用于更新 state(状态) 。它接受一个新的 state(状态) 值,并将组件排入从新渲染的队列。git
const id = props;
const [value, setValue] = useState(1)
useEffect(() => {
dosomething();
},[id, value]);
复制代码
useEffect 这个反作用函数在react全生命周期中扮演着很重要的角色,与 componentDidMount 和 componentDidUpdate 不一样,传递给 useEffect 的函数在延迟事件期间在 layout(布局) 和 paint(绘制) 后触发。咱们也能够把useEffect看做是生命周期函数的一个集合,以前在生命周期中didMount,didUpdate,WillReceiveProps,WillUnmount均可以将函数做为第一个参数dosomething在useEffect执行。
第一个参数为函数dosomething(),第二个参数为一个数组,数组里面的id和value只要有一个改变都会执行dosomething()。github
useEffect(() => {
getDeviceSituation(projectId);
}, [getDeviceSituation, projectId]);
const getDeviceSituation = useCallback((id) => {
dispatch({
type: 'runTimeCenter/getDeviceSituation',
payload: {
projectId: id,
},
});
}, [dispatch]);
const onClickTag = () => {
getDeviceSituation(projectId);
};
return (
<div onclick = {onClickTag}></div>
)
复制代码
两种用途
react-native
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
复制代码
2.实例化字段,方便保留任何可变值数组
const string = useRef('aaa');
复制代码
function useInputValue(initialValue) {
const [value, setValue] = useState(initialValue);
const onChange = (event) => {
setValue(event.currentTarget.value);
};
return {
value,
onChange
};
}
function Demo(props){
const name = useInputValue('sss')
return (
<input {...name} />
)
}
复制代码
是否是感受代码很清爽,这样我就能够将全部的组件Hooks化,说白了自定义Hooks,也就是自定义组件。bash