如何在 usereducer react/ts 中翻转状态

how to flip state in usereducer react/ts

我正在尝试设置 usereducer,我希望能够翻转 hasStarted(布尔值)的状态。我是打字稿的新手,似乎无法弄清楚如何正确实施它。这是我的代码(抱歉,这段代码可能有很多问题)

import React from "react";

const ACTIONS = {
  FLIP: "flipHasStarted"
}

type State = {
  hasStarted: boolean;
};

type Action = {
  type: "flip";
};

const reducer = (state: State, action: Action) => {
  switch (action.type) {
    case ACTIONS.FLIP:
      return {...state, hasStarted: !hasStarted}
  }
  return state;
};

const initialState = {
  hasStarted: false,
};

export const App = () => {
  const [state, dispatch] = React.useReducer(reducer, initialState);

  return (
    <>
      <button onClick={() => dispatch(flipHasStarted)} className="bg-yellow-500 p-8">
        TEST
      </button>
    </>
  );
};

如我所见,在您的代码中未定义 flipHasStarted,因此您应该像这样提供一个要分派的动作对象

 <button onClick={() => dispatch({
     type:ACTIONS.FLIP
     })} className="bg-yellow-500 p-8">
    TEST
  </button>

你的动作定义有点混乱,我这样修正了它:

import React from "react";

// Action types
const FLIP_ACTION = "FLIP_ACTION";

type ActionType = typeof FLIP_ACTION;

type Action = {
    type: ActionType;
};

// Action creators
const flip = (): Action => ({
    type: FLIP_ACTION,
});

// State

type State = {
    hasStarted: boolean;
};

const initialState = {
    hasStarted: false,
};

// Reducer
const reducer = (state: State, action: Action) => {
    switch (action.type) {
        case FLIP_ACTION:
            return { ...state, hasStarted: !state.hasStarted };
        default:
            return state;
    }
};

export const App = () => {
    const [state, dispatch] = React.useReducer(reducer, initialState);

    return (
        <>
            <button
                onClick={() => dispatch(flip())}
                className="bg-yellow-500 p-8"
            >
                TEST
            </button>
        </>
    );
};

如果你想添加更多动作,你必须做4件事:

  1. 定义新的动作类型:

const SOME_ACTION = "SOME_ACTION";

  1. 更新ActionType定义

type ActionType = typeof FLIP_ACTION | typeof SOME_ACTION;

  1. 创建一个动作创建者(这是可选的,但它使动作调度更干净):

    const someAction = (): 动作 => ({ 类型:SOME_ACTION, });

  2. 在你的减速器中添加一个case