javascript - React-TypeScript : Expected 0 argumen

您好,我在 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/

相关文章:

c# - 如何转义和忽略 __debugbreak

javascript - 未捕获的类型错误 : Failed to resolve module s

java - 如何使用二维指针通过 JNA 调用 C 函数?

python - 如何授予应用程序(而非用户本身)对文件夹和文件的权限

javascript - 我如何构建一个用一组新按钮回复的不和谐按钮

javascript - 使用 react-chartjs-2 创建对折线图的引用

python - 直接查询 Sqlalchemy-utils EncrytedType 作为 SQL

python - SQLAlchemy 不插入默认值

java - Vertx 运行多个事件循环

javascript - javascript(ASP.Net)中的计时器倒计时