我正在学习 react 和 typescript。我正在尝试使用 useReducer 构建一个 todo 应用程序,但遇到了一些错误。不知道它们是否有关联。
我的代码如下
import { useReducer, useState } from "react";
import { Sidebar } from "../components/Sidebar";
interface State {
todos: [];
}
enum ActionType {
Add = "ADD",
Remove = "REMOVE",
}
interface Action {
type: ActionType;
payload: {
id: string;
title: string;
};
}
const initialState: State = {
todos: [],
};
const reducer = (state: State, action: Action) => {
switch (action.type) {
case ActionType.Add:
return [
...state.todos,
{ id: action.payload.id, title: action.payload.title },
];
case ActionType.Remove:
default:
return state.todos;
}
};
export const Todo = () => {
const [state, dispatch] = useReducer(reducer, initialState); // first mistake is here
const [input, setInput] = useState<string>("");
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
// second mistake is here
dispatch({
type: ActionType.Add,
payload: { id: crypto.randomUUID(), title: input },
});
};
return (
<>
<Sidebar />
<div className="main">
<form onSubmit={(e) => handleSubmit(e)}>
<input type="text" onChange={(e) => setInput(e.target.value)} />
<button>add</button>
</form>
</div>
</>
);
};
第一个错误是: useReducer 说“没有过载匹配此调用……”
第二个是当我调用 dispatch 时它说“预期 0 个参数,但得到 1 个”
提前感谢你的帮助。
您的状态是一个对象,具有单个属性 -
todos
,它应该是项目数组Todo
。reducer 应该采用原始状态,并返回具有相同形状的新状态(或相同状态)。当您添加项目时,或者在默认类型下,您只会返回 数组todos
。此外,有效负载是待办事项,但todos
只是一个没有项目类型的数组。参见代码中的注释(TS 游乐场):