Reducer模式

在直接调用setter之前,使用动作汇总状态更改规则时更为合适。


命名reducer状态

createRxReducer通过dispatch动作而不是直接更改状态。适用于购物车、待办事项、编辑器状态等有多个更改规则的状态。

tsx
type TodoAction =
  | { type: "add"; text: string }
  | { type: "toggle"; id: number }
  | { type: "clearDone" };

function todoReducer(state: TodoState, action: TodoAction): TodoState {
  switch (action.type) {
    case "add":
      return {
        items: [...state.items, { id: state.nextId, text: action.text, done: false }],
        nextId: state.nextId + 1,
      };
    case "toggle":
      return {
        ...state,
        items: state.items.map((item) =>
          item.id === action.id ? { ...item, done: !item.done } : item,
        ),
      };
    default:
      return state;
  }
}

const { dispatchTodo, useTodo } = createRxReducer(
  initialTodoState,
  todoReducer,
  "todo",
);

运行时键使用reducer元组助手

如果需要为每个运行时键分离reducer存储,如工作区ID、项目ID等 createRxReducerTuple请使用。

tsx
export function useWorkspaceFilterState(workspaceId: string) {
  return createRxReducerTuple(
    initialFilterState,
    filterReducer,
    `workspace-filter:${workspaceId}`,
    { storage: "auto" },
  );
}
© 2026 Byeolnaerim. 保留所有权利.介绍隐私政策