我想为我从事的项目中的用户创建一个 Redux 切片。我有 this code sandbox,但我不知道为什么 fetchAll
文件中的 MyButton.tsx
调用出现以下错误:
fetchAll(arg: any): AsyncThunkAction
需要 1 个参数,但得到 0 个。
createAsyncThunk.d.ts(107, 118):未提供“arg”的参数。
我在我从事的项目中有类似的代码,它没有这个错误。我希望这能像在其他类似文件中一样工作。
沙箱中的相关文件:
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>
);
};
export const fetchAll = createAsyncThunk(
"users/fetchAll",
async (_: any, thunkAPI) => {
const users = await new Promise((resolve, reject) => {
resolve(["a", "b", "c"]);
});
return users;
}
);
如果我调用 fetchAll(null)
而不是 fetchAll()
,效果很好。
答案 0 :(得分:1)
如果您不想要该参数,请使用 void
类型。 any
强制一个参数。
export const fetchAll = createAsyncThunk(
"users/fetchAll",
async (_: void, thunkAPI) => {
const users = await new Promise((resolve, reject) => {
resolve(["a", "b", "c"]);
});
return users;
}
);
答案 1 :(得分: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;
});