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

sil*_*gan 4 dispatch typescript redux react-redux redux-toolkit

我想为我所从事的项目内的用户创建一个 Redux 切片。我有这个代码沙箱fetchAll,我不知道为什么文件中的调用出现以下错误MyButton.tsx

fetchAll(arg:any): AsyncThunkAction<未知,任意,{}>

预期有 1 个参数,但得到 0 个。

createAsyncThunk.d.ts(107, 118):未提供“arg”参数。

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

沙箱中的相关文件:

我的按钮.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>
  );
};
Run Code Online (Sandbox Code Playgroud)

fetchAll 的定义

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

    return users;
  }
);
Run Code Online (Sandbox Code Playgroud)

更新1

如果我打电话fetchAll(null)而不是fetchAll(),效果很好。

phr*_*hry 9

void如果您不需要该参数,请使用该类型。any强行提出一个论点。

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

    return users;
  }
);
Run Code Online (Sandbox Code Playgroud)


ale*_*ero 5

如果你想指定类型:

interface IThunkApi {
  dispatch: AppDispatch,
  state: IRootState,
}

export const fetchAll = createAsyncThunk<
string[], // return type
void, // args type
IThunkApi, // thunkAPI type
>("users/fetchAll", async (args, thunkAPI) => {
  const users = await new Promise((resolve, reject) => {
    resolve(["a", "b", "c"]);
  });
   return users;
});
Run Code Online (Sandbox Code Playgroud)