|
|
|
@ -5,7 +5,8 @@
@@ -5,7 +5,8 @@
|
|
|
|
|
const [state, dispatch] = useReducer(reducer, initialArg, init); |
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
React 官网的 useReducer 实现计数器案例 |
|
|
|
|
React 官网的 useReducer |
|
|
|
|
|
|
|
|
|
```javascript |
|
|
|
|
const initialState = {count: 0}; |
|
|
|
|
|
|
|
|
@ -30,4 +31,15 @@ function Counter() {
@@ -30,4 +31,15 @@ function Counter() {
|
|
|
|
|
</> |
|
|
|
|
); |
|
|
|
|
} |
|
|
|
|
``` |
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
最简的 useReducer 实践 |
|
|
|
|
|
|
|
|
|
```javascript |
|
|
|
|
const [state, dispatch] = useReducer((state, action) => ( |
|
|
|
|
{ ...state, action }), |
|
|
|
|
initState |
|
|
|
|
) |
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
在这个最简单的事件中,useReducer 就充当了 useState 的替代,dispatch 修改状态,返回最新的 state |