useState 的一个代替方案,适合于 state 逻辑较复杂且包含多个子值,或者下一个 state 依赖于之前的 state 等。
const [state, dispatch] = useReducer(reducer, initialArg, init);
- reducer
(state, action) => {}
- initialArg 默认值
- init 惰性初始化 ```jsx function init(initialCount) { return {count: initialCount}; }
function reducer(state, action) { switch (action.type) { case ‘increment’: return {count: state.count + 1}; case ‘decrement’: return {count: state.count - 1}; case ‘reset’: return init(action.payload); default: throw new Error(); } }
function Counter({initialCount}) { const [state, dispatch] = useReducer(reducer, initialCount, init); return ( <> Count: {state.count} </> ); } ```