hooks可以在不编写class组件的情况下使用state
1、useState会返回一对值:当前状态和一个更新值的函数
const [state, setState] = useState(initialState)
2、useEffect就是一个effect hooks,给函数组件增加了操作副作用的能力。相当于componentDidMount,componentDidUpdate,componentWillUnmount合成的api
componentWillUnmount: useEffect(() => {}, [])
componentDidUpdate: useEffect(() => {}, [value])
componentWillUnmount: useEffect(() => {return() => {}}, [])
3、useLayoutEffect:函数签名与useEffect相同,但它会在所有的dom变更之后同步调用effect
useEffect不会阻塞浏览器渲染,而useLayoutEffect会阻塞浏览器渲染
useEffect会在浏览器渲染结束后执行,而useLayoutEffect则是在dom更新完成以后,浏览器绘制之前执行
4、使用useMemo和useCallback来减少渲染
import React from 'react';
import ReactDOM from 'react-dom';
let Child = ({ onBtnClick, data }) => {
console.log("Child render");
return <button onClick={onBtnClick}>{data.number}</button>;
}
Child = React.memo(Child);
function App() {
const [number, setNumber] = React.useState(0);
const [name, setName] = React.useState("baobao");
const addClick = React.useCallback(() => setNumber(number + 1), [number]);
const data = React.useMemo(() => ({ number }), [number]);
return (
<div>
<input value={name} onChange={(e) => setName(e.target.value)} />
<Child onBtnClick={addClick} data={data} />
</div>
);
}
5、useContext:接收一个context对象并返回该context的当前值
6、useReducer:接收一个形如 (state, action) => newState 的 reducer,并返回当前的 state 以及与其配套的 dispatch 方法
import React from 'react';
import ReactDOM from 'react-dom';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return state+1;
case 'decrement':
return state-1;
default:
throw new Error();
}
}
function App(){
const [state, dispatch] = React.useReducer(reducer, 0);
return (
<>
Count: {state}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
)
}
更多博文:
useReducer