我不知道为什么我在减速器上出错
减速器代码
for
发生错误
case ADD_COMMENT_SUCCESS: {
const postIndex = state.mainPosts.findIndex(v => v.id === action.data.postId);
const post = state.mainPosts[postIndex];
const Comments = [...post.Comments, action.data.comment];
const mainPosts = [...state.mainPosts];
mainPosts[postIndex] = { ...post, Comments };
return {
...state,
isAddingComment: false,
mainPosts,
commentAdded: true,
};
}
git: https://github.com/hyunsokstar/node_bird_33
https://github.com/hyunsokstar/node_bird_33/blob/master/front/reducers/post.js
https://github.com/hyunsokstar/node_bird_33/blob/master/front/components/PostCard.js
感谢让我知道如何解决
答案 0 :(得分:1)
我想这是因为在findIndex
不匹配的情况下,undefined
返回了id
,并导致了类似undefined.Comments
的错误。
case ADD_COMMENT_SUCCESS: {
const postIndex = state.mainPosts.findIndex(v => v.id === action.data.postId);
if(postIndex){
const post = state.mainPosts[postIndex];
const Comments = [...post.Comments, action.data.comment];
const mainPosts = [...state.mainPosts];
mainPosts[postIndex] = { ...post, Comments };
return {
...state,
isAddingComment: false,
mainPosts,
commentAdded: true,
};
}
else{
// Write Your logic if the index is not found
return state;
}