我想使用id替换对象数组中的对象来查找它,
有效负载具有新对象

const initialState = {
  allComments: []
};

case LIKE_COMMENT:
      let index = state.allComments.findIndex(
        value => value._id === payload._id
      );
      if (index === -1) {
        return {
          ...state,
          allComments: [...state.allComments, ...payload]
        };
      } else {
        return {
          ...state,
          allComments: [
            (state.allComments[index] = payload),
            ...state.allComments
          ]
        };
      }


他们的问题是,它继续推动该对象而不替换上一个对象

最佳答案

 case LIKE_COMMENT:
      return {
        ...state,
        allComments: state.allComments.map(comment => {
          if (comment.id === payload._id) return payload;
          return comment;
        })
      }


这将用有效负载替换注释并返回所有其他注释

09-11 18:20