React
useReducer
作为 useState
的代替方案,在某些场景下使用更加适合,例如 state 逻辑较复杂且包含多个子值,或者下一个 state 依赖于之前的 state 等。
使用 useReducer
还能给那些会触发深更新的组件做性能优化,因为父组件可以向自组件传递 dispatch 而不是回调函数
const [state, dispatch] = useReducer(reducer, initialArg, init);
方法使用
import React, { useReducer } from 'react'
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();
}
}
export default function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
初始化 state
useReducer 初始化 sate 的方式有两种
// 方式1
const [state, dispatch] = useReducer(
reducer,
{count: initialCount}
);
// 方式2
function init(initialClunt) {
return {count: initialClunt};
}
const [state, dispatch] = useReducer(reducer, initialCount, init);