gpt4 book ai didi

redux - 如何在 `createAsyncThunk` 状态下在 "pending"上发送自定义参数?

转载 作者:行者123 更新时间:2023-12-05 00:56:02 26 4
gpt4 key购买 nike

fetchUserById() 创建时,它的输出响应被定义。

const fetchUserById = createAsyncThunk<{user: UserInterface, id: number}, number>(
'users/fetchByIdStatus',
async (userId) => {
const response = await userAPI.fetchById(userId)
return {user: response.data, id: userId}
}
);

const userSlice = createSlice({
name: "users",
initialState: [],
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchUserById.pending, (state, { payload }) => {
// how I configured custom value for this payload?
// I need to send the user id.
});
builder.addCase(fetchUserById.fulfilled, (state, {payload}) => {
/**
* @var {UserInterface} user
* @var {number} id;
*/
const {id, user} = payload;
state[id].loading = false;
state[id].user = user;
});
},
});

但是当操作处于“待处理”状态时如何定义响应?

最佳答案

您传递给 createAsyncThunk 的 arg 将在 action.meta.arg 中可用。所以在你的例子中,你可以这样引用:

builder.addCase(fetchUserById.pending, (state, { meta }) => {
console.log(meta.arg); // meta.arg will have whatever value was passed as `userId`
});

关于redux - 如何在 `createAsyncThunk` 状态下在 "pending"上发送自定义参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63074989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com