【问题标题】:Merging redux objects合并 redux 对象
【发布时间】:2021-07-28 00:27:45
【问题描述】:

我正在使用 redux 来持久化 React.JS 应用程序的状态。

状态保留名为 event 的对象,这些对象看起来像 {id: 2, title: 'my title', dates: [{start: '02-05-2021', end: '02-05-2021'}] } 由对象 ID 散列。

我从后端提取对象并将它们与现有状态合并,在我的 reducer 中,如下所示:

case LOAD_SUCCESS:
  draft.loading = false;
  draft.events = {
    ...state.events,
    ...action.events.reduce((acc, val) => {
      return { ...acc, [val.id]: val };
    }, {})
  };
  break;

这很好用,通过新拉取的版本添加/替换已经处于状态的对象。

但这并不是我所需要的。我想选择event 对象的后者action.events 版本,dates 除外。我想要合并然后重复数据删除的日期,例如删除重复项。

基本上,如果国家有

{
  2: {
    id: 2,
    title: 'my title',
    dates: [{
      start: '02-05-2021',
      end: '02-05-2021'
    }]
  }
}

我拉了

[{
  id: 2,
  title: 'my new title',
  dates: [{
    start: '03-06-2021',
    end: '03-06-2021'
  }]
}]

合并后的结果状态应该是

{
  2: {
    id: 2,
    title: 'my new title',
    dates: [{
      start: '02-05-2021',
      end: '02-05-2021'
    }, {
      start: '03-06-2021',
      end: '03-06-2021'
    }]
  }
}

【问题讨论】:

  • 在你的减速器中,你也可以尝试合并你的日期。
  • immutable.js 标签有误吗?问题或答案都没有显示使用该库的任何内容。

标签: javascript reactjs react-redux immutable.js


【解决方案1】:

您可以通过以下方式将现有日期与新日期合并:

const state = {
  2: {
    id: 2,
    title: 'my title',
    dates: [{ start: '02-05-2021', end: '02-05-2021' }]
  }
};

const update = [{
  id: 2,
  title: 'my new title',
  dates: [{ start: '03-06-2021', end: '03-06-2021' }]
}];

const merged = {
  ...update.reduce((newState, { id, title, dates }) => ({
    ...newState,
    [id] : {
      ...newState[id],
      title,
      dates: [...newState[id]?.dates, ...dates]
    }
  }), state)
};

console.log(merged);
.as-console-wrapper { top: 0; max-height: 100% !important; }

【讨论】:

    【解决方案2】:

    在你的减速器内部:

    action.events.reduce((acc, val) => {
        const existingDates = state.events[val.id]?.dates || [];
        const dates = [...val.dates, ...existingDates];
        return { ...acc, [val.id]: {...val, dates} };
    }, {})
    

    如果您需要删除重复项,请参阅this answer

    【讨论】:

      猜你喜欢
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      • 2017-01-01
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多