[英]React-TypeScript: Expected 0 arguments, but got 1 on a useReducer
greetings im having a little of a trouble implementing an useReducer in a typeStript application, i have several mistakes (all of then on the reducer) but this one is the most commom throu the app, every single time that i call the dispatch function it jumps the error of "Expected 0 arguments, but got 1"问候我在 typeStript 应用程序中实现 useReducer 时遇到了一些问题,我有几个错误(所有错误都在减速器上),但这是应用程序中最常见的错误,每次我调用调度函数时它都会跳转“预期 0 个参数,但得到 1 个”的错误
this is the function of the reducer这是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;
};
the reducer and one of the dispatchs减速器和其中一个调度
const [todos, dispatch] = useReducer(reducerFunction, []);
/*-----------*/
dispatch({ type: "add", payload: todo });
you can watch the whole app in this codesanbox: https://codesandbox.io/s/trello-todo-component-clone-ebpqw4?file=/src/App.tsx:1465-1507您可以在此代码框中观看整个应用程序: https ://codesandbox.io/s/trello-todo-component-clone-ebpqw4?file=/src/App.tsx:1465-1507
In order for TypeScript to infer the type of the state, you need to add a return type to reducerFunction
.为了让 TypeScript 推断状态的类型,您需要向
reducerFunction
添加返回类型。
const reducerFunction = (state: Todo[], actions: Actions): Todo[]
Alternatively, you can add the type of reducerFunction
to the useReducer
call.或者,您可以将
useReducer
reducerFunction
中。
const [todos, dispatch] = useReducer<(arg1: Todo[], actions: Actions) => Todo[]>(reducerFunction, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.