useReducer
-
useReducer 和 redux 中 reducer 很像
-
useState 内部就是靠 useReducer 来实现的
-
useState 的替代方案,它接收一个形如 (state, action) => newState 的 reducer,并返回当前的 state 以及与其配套的 dispatch 方法
-
在某些场景下,useReducer 会比 useState 更适用,例如 state 逻辑较复杂且包含多个子值,或者下一个 state 依赖于之前的 state 等
基本用法
const [state, dispatch] = useReducer(reducer, initialArg, init);
const initialState = 0;
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {number: state.number + 1};
case 'decrement':
return {number: state.number - 1};
default:
throw new Error();
}
}
function init(initialState){
return {number:initialState};
}
function Counter(){
const [state, dispatch] = useReducer(reducer, initialState,init);
return (
<>
Count: {state.number}
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
)
}
useReducer 接收三个参数:
reducer:一个函数,用于根据当前的状态和动作来计算新的状态。initialState:初始状态的值。
另外,useReducer 还可以接收一个可选的第三个参数:
initialAction:初始动作的值。这个参数通常不常用,它可以用来在组件挂载时立即触发一次状态更新。