我们以计数器为例(简单的通过点击来实现 +1 与 -1)
先定义并创建一个useReducer
const [count, dispacth] = useReducer(reducer, 0)
count:我们自己定义的变量。
dispatch:状态感知器。传递状态,并牵引 reducer 函数的调用。
reducer:通过识别 dispatch 中传递的 action,从而选择状态,做出相应的操作。
0:count 的初始值。
关于 reducer 函数
function countReducer(count, action) {
switch (action.type) {
case 'add':
return count + 1;
case 'sub':
return count - 1;
default:
return count;
}
}
关于按钮的点击事件
<button onClick={() => { dispatch({ type: 'add' }) }}>click me +</button>
<button onClick={() => { dispatch({ type: 'sub' }) }}>click me -</button>
小结:
感觉 useReducer 的出现,是为了弥补 useState 只能管理单一状态的漏洞。