如何将Async Thunk中的ID传递至Extra Reducer?
解决Redux Toolkit中Async Thunk参数传递到Extra Reducer的问题
问题场景
我正在派发id以删除posts数组中的特定帖子,但接口仅返回成功提示信息,导致无法在Extra Reducer的fulfilled分支中获取到id来过滤数组。
当前Delete Thunk代码:
// 删除Thunk export const deletePost = createAsyncThunk("deletePost", async (action) => { console.log("🚀 ~ deletePost ~ action", action) // 此处可获取ID const response = await deletePos(action); return response.data; });
对应Extra Reducer代码:
builder.addCase(deletePost.fulfilled, (state, action) => { console.log(action) state.posts = state.posts.filter((post) => post._id !== action.payload); state.loading = false; });
解决方案
方法1:在Thunk返回值中包含ID
直接将传入的ID与接口响应数据一起返回,让Extra Reducer从action.payload中读取ID:
export const deletePost = createAsyncThunk("deletePost", async (postId) => { console.log("🚀 ~ deletePost ~ postId", postId) const response = await deletePos(postId); return { id: postId, message: response.data }; });
修改后的Extra Reducer:
builder.addCase(deletePost.fulfilled, (state, action) => { state.posts = state.posts.filter((post) => post._id !== action.payload.id); state.loading = false; });
方法2:使用Async Thunk的meta.arg属性
createAsyncThunk会自动将传入Thunk的参数存入action.meta.arg,无需修改Thunk返回值,直接在Extra Reducer中读取:
// Thunk代码保持不变 export const deletePost = createAsyncThunk("deletePost", async (postId) => { console.log("🚀 ~ deletePost ~ postId", postId) const response = await deletePos(postId); return response.data; });
修改后的Extra Reducer:
builder.addCase(deletePost.fulfilled, (state, action) => { state.posts = state.posts.filter((post) => post._id !== action.meta.arg); state.loading = false; });
内容的提问来源于stack exchange,提问作者Sohaib Butt
相关产品推荐
相关产品推荐

