当 state 变复杂时,useState 会开始散乱:一会儿改温度,一会儿改模式,一会儿记错误信息,一会儿处理异步状态。
function reducer(state, action) {
switch (action.type) {
case 'power/toggle':
return { ...state, isOn: !state.isOn };
case 'temp/up':
return { ...state, temp: state.temp + 1 };
case 'mode/set':
return { ...state, mode: action.payload };
default:
return state;
}
}
function AirConditioner() {
const [state, dispatch] = useReducer(reducer, {
isOn: false,
temp: 26,
mode: 'cool',
});
return (
<div>
<p>{state.temp}°C</p>
<button onClick={() => dispatch({ type: 'temp/up' })}>升温</button>
</div>
);
}useState vs useReducer:
| useState | useReducer | |
|---|---|---|
| 适合 | 简单局部状态 | 复杂状态机 |
| 更新逻辑 | 分散在各处 | 集中在 reducer |
| 类比 | 单个按钮直连 | 中央控制器调度 |