深入理解React的useReducer

100 阅读1分钟

什么是useReducer

useReducerReact 提供的一个用于状态管理的 Hook,它借鉴了 Redux 的核心思想,适合管理复杂的状态逻辑。与 useState 相比, useReducer 更适合处理包含多个子值的状态对象,或者当下一个状态依赖于之前的状态时。

const [state, dispatch] = useReducer(reducer, initialState);

代码示例分析

我们来看一个计数器示例:

const initialState = {
  count: 0,
  isLogin: false,
  theme: 'light'
};
  1. 创建reducer函数
const reducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    case 'incrementByNum':
      return { count: state.count + parseInt(action.payload) };
    default:
      return state;
  }
};
  1. 在组件中使用

function App() {
  const [count, setCount] = useState(0);
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      <input 
        type="text" 
        value={count} 
        onChange={(e) => setCount(e.target.value)} 
      />
      <button 
        onClick={() => dispatch({ type: 'incrementByNum', payload: count })}
      >
        incrementByNum
      </button>
    </>
  );
}

效果

Reducer1.gif

useReducer的优势

  1. 逻辑集中管理 :所有状态更新逻辑都集中在reducer函数中
  2. 可预测性 :状态更新遵循固定的模式(action → reducer → new state)
  3. 易于测试 :reducer是纯函数,不依赖组件实例
  4. 适合复杂状态 :当状态结构复杂或状态之间存在依赖关系时

适用场景

  • 表单状态管理(特别是多字段表单)
  • 实现撤销/重做功能
  • 复杂的状态逻辑
  • 全局状态管理(结合Context API)

总结

useReducer 提供了一种更结构化的状态管理方式,特别适合处理复杂的状态逻辑。虽然学习曲线比 useState 稍高,但在适当的场景下使用可以大大简化代码结构,提高可维护性。