在reducer成功请求后,我正在寻找类型错误的原因

时间:2019-11-16 04:38:19

标签: reactjs

我不知道为什么我在减速器上出错

enter image description here

减速器代码

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

感谢让我知道如何解决

1 个答案:

答案 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;

        }