如何在 Redux 中的 asyncThunk.fulfilled 操作期间更新数组中的对象
how to update an object within an array during an asyncThunk.fulfilled action in Redux
我有一个名为 likePost
的 AsyncThunk 方法,当用户在 post 上单击 like
时,它将通过调度发送此操作。该方法运行良好,在我的数据库中 Post
已成功更新,但我无法让 Redux 更新 .fulfilled
方法期间喜欢的 Post。
这是我目前正在使用的东西:
// shoes = [{_id: '', title: '', likes: []}, ...{}]
export const likePost = createAsyncThunk(
'posts/likePost',
async (payload, { rejectWithValue }) => {
try {
const response = await userTokenAxios.post(`/${payload}/like`);
return response.data;
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
[likePost.fulfilled]: (state, action) => {
const post = state.posts.find((post) => post._id === action.payload._id);
post.likes.push(action.payload.user);
},
不是查找 post,而是在 state.posts 中获取该对象的索引
const post = state.posts.find((post) => post._id === action.payload._id);
const postIndex=state.posts.findIndex((post)=> post._id === action.payload._id);
现在您可以将 user
推送到 likes 数组中:
state.posts[postIndex].likes.push(action.payload.user)
我有一个名为 likePost
的 AsyncThunk 方法,当用户在 post 上单击 like
时,它将通过调度发送此操作。该方法运行良好,在我的数据库中 Post
已成功更新,但我无法让 Redux 更新 .fulfilled
方法期间喜欢的 Post。
这是我目前正在使用的东西:
// shoes = [{_id: '', title: '', likes: []}, ...{}]
export const likePost = createAsyncThunk(
'posts/likePost',
async (payload, { rejectWithValue }) => {
try {
const response = await userTokenAxios.post(`/${payload}/like`);
return response.data;
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
[likePost.fulfilled]: (state, action) => {
const post = state.posts.find((post) => post._id === action.payload._id);
post.likes.push(action.payload.user);
},
不是查找 post,而是在 state.posts 中获取该对象的索引 const post = state.posts.find((post) => post._id === action.payload._id);
const postIndex=state.posts.findIndex((post)=> post._id === action.payload._id);
现在您可以将 user
推送到 likes 数组中:
state.posts[postIndex].likes.push(action.payload.user)