useReducer
优质
小牛编辑
125浏览
2023-12-01
useState 的替代方案。 接受类型为 (state, action) => newState 的 reducer,并返回与 dispatch 方法配对的当前状态。 (如果你熟悉 Redux,你已经知道它是如何工作的。)
下面例子 useState 部分的计数器示例,重写为使用 reducer:
import { useReducer } from 'rax';
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'reset':
return initialState;
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
// A reducer must always return a valid state.
// Alternatively you can throw an error if an invalid action is dispatched.
return state;
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, {count: initialCount});
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'reset'})}>
Reset
</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</>
);
}