首页 > 解决方案 > Redux - 如何将项目添加到某些属性中

问题描述

我真的很挣扎,我想在我的“binnacleNotesReducer”中的“binnacleNotes”属性中添加一个新项目,我尝试了几种我在互联网上发现的方法,但效果不佳。

新注释要么被添加到主属性“binnaceNotesReducer”中,要么不被添加。

我有以下redux结构:

在此处输入图像描述

请参考我在下面代码中的几次尝试:

case ADD_NEW_NOTE:
      const { id, date, binnacle_note, responsibleState, attachments, constructor_review, super_review, dro_review, timestamp } = payload;
      const newNote = {
        binnacleNotes: {
          id,
          date,
          binnacle_note,
          responsibleState,
          attachments,
          constructor_review,
          super_review,
          dro_review,
          timestamp,
        },
      };
      //return state.binnacleNotes.concat(newNote);
      return {
        ...state.binnacleNotes,
        binnacleNotes: {
          ...state.binnacleNotes,
          id,
          date,
          binnacle_note,
          responsibleState,
          attachments,
          constructor_review,
          super_review,
          dro_review,
          timestamp,
        },
      };

不同的方法:

   case ADD_NEW_NOTE:
      const { id, date, binnacle_note, responsibleState, attachments, constructor_review, super_review, dro_review, timestamp } = payload;
      const newNote = {
        binnacleNotes: {
          id,
          date,
          binnacle_note,
          responsibleState,
          attachments,
          constructor_review,
          super_review,
          dro_review,
          timestamp,
        }
      }
      return state.binnacleNotes.concat(newNote);

标签: reactjsreduxreact-redux

解决方案


阅读更多文档后,我找到了解决方案,希望这对任何人都有帮助:

case ADD_NEW_NOTE:
      const { id, date, binnacle_note, responsible, attachments, constructor_review, super_review, dro_review, timestamp } = payload;
      return {
        binnacleNotes: [
          ...state.binnacleNotes,
          { id, date, binnacle_note, responsible, attachments, constructor_review, super_review, dro_review, timestamp },
        ],
      };

推荐阅读