Skip to content

useReducer

一句话解释

useReducer 是 Hook 那个 manages 状态 using reducer 函数 (如 Redux) — ideal for 复杂状态 logic 使用多个 sub-值.

用大白话说

useReducer 是 alternative 到 useState for managing complex state. Instead of calling a setter with a new value, you dispatch actions, and a reducer function decides how to update the state based on the action type.

The pattern is: const [状态, dispatch] = useReducer(reducer, initialState). The reducer is a pure function (状态, 操作) => newState. You call dispatch({ 类型: 'increment' }) and the reducer handles it.

useReducer is preferable when: state has multiple related sub-values, the next state depends on the previous in complex ways, or you want to centralize and test your state logic. It is the same pattern used by Redux, making it a natural stepping stone to Redux.

示例

jsx
function reducer(state, action) {
  switch (action.type) {
    case "increment": return { count: state.count + 1 };
    case "decrement": return { count: state.count - 1 };
    default: return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });
  return <button onClick={() => dispatch({ type: "increment" })}>{state.count}</button>;
}

reducer handles 'increment' and 'decrement' 操作. 组件 dispatches 操作相反的 calling setter directly.

相关术语

相关资源

相关课程

  • useReducer

    学习 useReducer for 复杂状态 management.

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表