Reactjs I';我正在寻找一个类型错误的原因,在一个来自reducer的成功请求之后
我不知道为什么我在减速器上出错 减速机代码Reactjs I';我正在寻找一个类型错误的原因,在一个来自reducer的成功请求之后,reactjs,Reactjs,我不知道为什么我在减速器上出错 减速机代码 case ADD_COMMENT_SUCCESS: { const postIndex = state.mainPosts.findIndex(v => v.id === action.data.postId); const post = state.mainPosts[postIndex]; const Comments = [...post.Commen
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,
};
}
此文件中出现错误
const Comments = [...post.Comments, action.data.comment];
吉特:
感谢您让我知道如何修复它我想这是因为
findIndex
在id
s不匹配的情况下返回undefined
,这会导致类似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;
}
请检查
post.Comments
,如果它不是数组,将引发异常。