本文内容大部分来源于官网
const [state, dispatch] = useReducer(reducer, initialArg, init);
useState 的替代方案。它接收一个形如 (state, action) => newState 的 reducer,并返回当前的 state 以及与其配套的 dispatch 方法。(如果你熟悉 Redux 的话,就已经知道它如何工作了。)
示例
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
使用场景
- state 逻辑较复杂且包含多个子值
- 下一个 state 依赖于之前的 state
- 向子组件传递回调函数用于更新父组件state时,可以传递
dispatch而不是回调函数 。
好在哪
- 可以处理较复杂且包含多个子值的state
- 处理effect中频繁变化的值
- 状态提升时向子组件传递dispatch而不是函数回调,降低错综复杂的管道工程