You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
# 简单的 React 思考 - useReducer
|
|
|
|
在一些需要连续更新状态的场景下,useReducer 会比 useState 更加的合适
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
const [state, dispatch] = useReducer(reducer, initialArg, init);
|
|
|
|
```
|
|
|
|
|
|
|
|
React 官网的 useReducer
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
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();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function Counter() {
|
|
|
|
const [state, dispatch] = useReducer(reducer, initialState);
|
|
|
|
return (
|
|
|
|
<>
|
|
|
|
Count: {state.count}
|
|
|
|
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
|
|
|
|
<button onClick={() => dispatch({type: 'increment'})}>+</button>
|
|
|
|
</>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
最简的 useReducer 实践
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
const [state, dispatch] = useReducer((state, action) => (
|
|
|
|
{ ...state, action }),
|
|
|
|
initState
|
|
|
|
)
|
|
|
|
```
|
|
|
|
|
|
|
|
在这个最简单的事件中,useReducer 就充当了 useState 的替代,dispatch 修改状态,返回最新的 state
|