嗨,我正在学习的每个人都用typeScript来反应钩子,我有useReducer的测试杆,我知道它是如何工作的,但是当我在我的项目中实现它时,我有错误。
const initalState: Istate = {
counter: 1,
name: "tt",
};
enum ActionKind {
increase = "INCREASE",
decrease = "DECREASE",
}
interface Action {
type: ActionKind;
payload: number;
}
interface Istate {
counter: number;
name: string;
}
function reducer(state: Istate, action: Action) {
switch (action.type) {
case "INCREASE":
return { count: state.counter + 1, name: state.name };
}
}
export function Hooktest() {
const [state, dispatch] = useReducer(reducer, initalState);
return (
<>
<button onClick={increment}>{counter}</button>
</>
);
}
我真的不明白色情或者我做错了什么

谢谢你的帮助
发布于 2022-10-06 14:42:54
减速器应该总是返回一个状态。向您的switch添加默认设置。此外,这一行还有一个错误:
return { count: state.counter + 1, name: state.name };根据您的类型,键count应该是counter。
你的减速机应该是这样的:
function reducer(state: Istate, action: Action) {
switch (action.type) {
case "INCREASE":
return { counter: state.counter + 1, name: state.name };
default:
return state;
}
}您的Hooktest组件应该使用dispatch和来自ActionKind枚举的相关操作:
export function Hooktest() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
<button onClick={() => dispatch({ type: ActionKind.increase })}>
{state.counter}
</button>
</>
);
}而且您应该将Action类型的payload更改为可选的,因为您不需要INCREASE操作的有效负载:
interface Action {
type: ActionKind;
payload?: number;
}您可以在这个沙盒中看到一个工作示例。
https://stackoverflow.com/questions/73975576
复制相似问题