在某些场景下,useReducer
会比 useState
更适用,例如 state 逻辑较复杂且包含多个子值,或者下一个 state 依赖于之前的 state 等。并且,使用 useReducer
还能给那些会触发深更新的组件做性能优化,因为你可以向子组件传递dispatch而不是回调函数。
const [state, dispatch] = useReducer(reducer, init);
useState 的替代方案。它接收一个形如 (state, action) => newState
的 reducer,并返回当前的 state 以及与其配套的 dispatch
方法,而 init 为 state 的初始值。
详细使用如下:
function Index () {
const [count, dispath] = useReducer((state, action) => {
switch (action.type) {
case 'increment':
return state + 1;
case 'decrement':
return state - 1;
default:
return state;
}
}, 0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => dispath({ type: 'decrement' })}>-</button>
<button onClick={() => dispath({ type: 'increment' })}>+</button>
</div>
)
}
在代码中通过 type 来表示 action 类型,如果 action 上的 type 为 increment 增加 state 也就是增加 count,如果 action 上的 type 为 decrement 减少 state 也就是减少 count 。
注意:如果 Reducer Hook 的返回值与当前 state 相同,React 将跳过子组件的渲染及副作用的执行。