【问题标题】:How to use createAsyncThunk from Redux Toolkit with TypeScript correctly?如何正确使用来自 Redux Toolkit 的 createAsyncThunk 和 TypeScript?
【发布时间】:2021-06-14 10:47:15
【问题描述】:

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

fetchAll(arg: any): AsyncThunkAction

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

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

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

沙盒中的相关文件:

MyButton.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(),效果很好。

【问题讨论】:

    标签: typescript redux react-redux dispatch redux-toolkit


    【解决方案1】:

    如果你想指定类型:

    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;
    });
    

    【讨论】:

      【解决方案2】:

      如果您不想要该参数,请使用 void 类型。 any 强制争论。

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

      【讨论】:

      • 有效!你能解释一下它是如何工作的吗?我认为 void 只是一个函数返回类型。我只看了TS手册。谢谢!
      • RTK 类型只是为了接受“无效”。自从我接管大部分类型维护之前就一直这样,所以我只是保持这种模式。
      猜你喜欢
      • 2021-08-23
      • 2022-01-22
      • 2020-09-13
      • 2021-09-17
      • 2020-09-26
      • 1970-01-01
      • 2021-12-24
      • 2021-09-11
      • 2021-09-01
      相关资源
      最近更新 更多