您好,我在 typeStript 应用程序中实现 useReducer 时遇到了一些麻烦,我有几个错误(所有错误都在 reducer 上)但是这个是整个应用程序中最常见的错误,每次我调用 dispatch函数它会跳转“Expected 0 arguments, but got 1”的错误
这是reducer的作用
interface Edit {
id?: number;
todo?: string;
}
type Actions =
{ type: "add"; payload: string }
| { type: "remove"; payload: number }
| { type: "done"; payload: number }
| { type: "all"; payload: Todo[] }
| { type: "edit"; payload: Edit };
const reducerFunction = (state: Todo[], actions: Actions) => {
const todoActions = {
add: [...state, { id: Date.now(), todo: actions.payload, isDone: false }],
edit: state.map((todo) =>
todo.id === actions.payload.id
? { ...todo, todo: actions.payload.todo }
: todo
),
remove: state.filter((todo) => todo.id !== actions.payload),
done: state.map((todo) =>
todo.id === actions.payload ? { ...todo, isDone: !todo.isDone } : todo
),
all: state = actions.payload
};
return todoActions[actions.type] ?? state;
};
reducer 和 dispatch 之一
const [todos, dispatch] = useReducer(reducerFunction, []);
/*-----------*/
dispatch({ type: "add", payload: todo });
您可以在这个 codesanbox 中观看整个应用程序: https://codesandbox.io/s/trello-todo-component-clone-ebpqw4?file=/src/App.tsx:1465-1507
最佳答案
为了让 TypeScript 推断状态的类型,您需要向 reducerFunction
添加返回类型。
const reducerFunction = (state: Todo[], actions: Actions): Todo[]
或者,您可以将 reducerFunction
的类型添加到 useReducer
调用中。
const [todos, dispatch] = useReducer<(arg1: Todo[], actions: Actions) => Todo[]>(reducerFunction, []);
关于javascript - React-TypeScript : Expected 0 arguments, 但在 useReducer 上得到 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72452178/