知食记
搜索文档…
useReducer

基本

useState 的替代方案。它接收一个形如 (state, action) => newState 的 reducer,并返回当前的 state 以及与其配套的 dispatch 方法。(如果你熟悉 Redux 的话,就已经知道它如何工作了。)
1
const [state, dispatch] = useReducer(reducer, initialArg, init);
Copied!

示例

1
const initialState = {count: 0};
2
3
function reducer(state, action) {
4
switch (action.type) {
5
case 'increment':
6
return {count: state.count + 1};
7
case 'decrement':
8
return {count: state.count - 1};
9
default:
10
throw new Error();
11
}
12
}
13
14
function Counter() {
15
const [state, dispatch] = useReducer(reducer, initialState);
16
return (
17
<>
18
Count: {state.count}
19
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
20
<button onClick={() => dispatch({type: 'increment'})}>+</button>
21
</>
22
);
23
}
Copied!
最近更新 1yr ago
复制链接