全书目录

第一篇:React 完全指南 —— 空调宇宙

第十八章:useReducer —— 中央控制器

1 分钟 163 字 第 40 / 962 个阅读单元

当 state 变复杂时,useState 会开始散乱:一会儿改温度,一会儿改模式,一会儿记错误信息,一会儿处理异步状态。

tsx
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
类比 单个按钮直连 中央控制器调度