YuJian
3 years ago
2 changed files with 34 additions and 3 deletions
@ -1,2 +1,33 @@
@@ -1,2 +1,33 @@
|
||||
# 简单的 React 思考 - useReducer |
||||
在一些需要连续更新状态的场景下,useReducer hui |
||||
在一些需要连续更新状态的场景下,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> |
||||
</> |
||||
); |
||||
} |
||||
``` |
Loading…
Reference in new issue