typescript - 如何正确使用 Redux Toolkit 中的 createAsyncThunk 和 TypeScript?

标签 typescript redux react-redux dispatch redux-toolkit

我想为我工作的项目中的用户创建一个 Redux 切片。我有 this code sandbox而且我不知道为什么 MyButton.tsx 文件中的 fetchAll 调用会出现以下错误:

fetchAll(arg: any): AsyncThunkAction<unknown, any, {}>

Expected 1 arguments, but got 0.

createAsyncThunk.d.ts(107, 118): An argument for 'arg' was not provided.

我在我工作的项目中有类似的代码,但没有这个错误。我希望它能像在其他类似文件中一样工作。

沙箱中的相关文件:

我的按钮.tsx

import React from "react";
import { useDispatch } from "react-redux";
import { fetchAll } from "./redux/usersSlice";

export const MyButton = ({ children }: { children: any }) => {
  const dispatch = useDispatch();

  return (
    <button
      onClick={() => {
        dispatch(fetchAll()); // I get an error on this fetchAll() call
      }}
    >
      {children}
    </button>
  );
};

fetchAll的定义

export const fetchAll = createAsyncThunk(
  "users/fetchAll",
  async (_: any, thunkAPI) => {
    const users = await new Promise((resolve, reject) => {
      resolve(["a", "b", "c"]);
    });

    return users;
  }
);

更新1

如果我调用 fetchAll(null) 而不是 fetchAll(),它运行良好。

最佳答案

如果您不需要该参数,请使用 void 类型。 any 强制一个参数。

export const fetchAll = createAsyncThunk(
  "users/fetchAll",
  async (_: void, thunkAPI) => {
    const users = await new Promise((resolve, reject) => {
      resolve(["a", "b", "c"]);
    });

    return users;
  }
);

关于typescript - 如何正确使用 Redux Toolkit 中的 createAsyncThunk 和 TypeScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67968873/

相关文章:

javascript - 匹配字符串中模式的出现并在 javascript 中插入字符?

javascript - 如何通过消除双重等待和 DRY 代码进行重构?

javascript - Redux + Hooks useDispatch() in useEffect calling action 两次

Firebase 登录 promise 在我点击屏幕上的任意位置后才能解决

javascript - 使用 Redux Saga 更新单个状态属性的最佳实践

Angular Material 选项卡 : Prevent tab change of mat-tab-group if the form in current tab is dirty

typescript - 从 KO observable 获取数字

reactjs - React 从 useEffect 中的 Redux 商店获取状态

javascript - 连接 NextJS、next-i18next、with-redux、with-redux-saga : "Error: If you have a getInitialProps method in your custom _app.js file..."

javascript - 如何在两个以上的 React 应用程序之间共享数据?