我试图设置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>
</>
);
};
在你的动作定义中有一点混乱,我像这样修复它:
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件事:
- 定义一个新的动作类型:
const SOME_ACTION = "SOME_ACTION";
- 更新
ActionType
定义
type ActionType = typeof FLIP_ACTION | typeof SOME_ACTION;
创建一个动作创建器(这是可选的,但它使动作调度更干净):
const someAction = (): Action =>({类型:SOME_ACTION,});
在你的减速机中添加
case
正如我所看到的,在你的代码中,flipHasStarted没有定义,所以你应该给一个动作对象来分派,像这样
<button onClick={() => dispatch({
type:ACTIONS.FLIP
})} className="bg-yellow-500 p-8">
TEST
</button>