合并两个不可变的地图

时间:2018-03-14 22:19:12

标签: reactjs redux immutable.js

我正在使用Redux和Immutable.js,我正在尝试过滤闪存卡序列,并将闪存卡设置为隐藏。然后使用redux返回该状态。我的数据模型如下所示:

"flashcardSequence": ["id1", "id2", "id3"],
  "flashcards": {
    "id1": {
      "cgi": "id1",
      "creatorGuid": "student1",
      "authoringType": "STUDENT",
      "sequence": 0,
      "hidden": false,
      "suppressed": false,
      "aspects": {
        "123": {
          "id": "123",
          "role": "Date",
          "value": [
            {
              "type": "text",
              "value": "1776"
            }
          ],
          "label": [
            {
              "type": "text",
              "value": "Date"
            }
          ]
        },

在我的flashcard reducer中,我的代码是:

 case types.HIDE_FLASHCARD: {
      const index = state
        .get('decks')
        .findIndex(i => i.get('deckCgi') === action.deckCgi);

      const card = state
        .getIn(['decks', index, 'flashcards'])
        .find(i => i.get('cgi') === action.cardId);

      const filteredSequence = state
        .getIn(['decks', index, 'flashcardSequence'])
        .filter(flashcardId => flashcardId !== action.cardId);

      // return state.setIn(
      //   ['decks', index, 'flashcardSequence'],
      //   filteredSequence
      // );

      let filteredSequenceState = state.setIn(
        ['decks', index, 'flashcardSequence'],
        filteredSequence
      );

      let hiddenCardState = state.setIn(
        ['decks', index, 'flashcards', action.cardId],
        card.set('hidden', true)
      );
      //I would like to combine both states into one single object without writing over any data.
      return filteredSequence + filteredSequenceState;
    }

我正在努力解决的问题是如何将这两种状态归还给我的应用程序?彼此独立地返回对象可以很好地工作,但我无法合并它们。我试图将它们与提供给我的方法合并无济于事。我想返回filteredSequence和hiddenCardState。

任何指导都将不胜感激。

感谢。

1 个答案:

答案 0 :(得分:1)

也许

const filteredSequenceState = state.setIn(
        ['decks', index, 'flashcardSequence'],
        filteredSequence
);

const hiddenCardState = filteredSequenceState.setIn(
        ['decks', index, 'flashcards', action.cardId],
        card.set('hidden', true)
);

return filteredSequenceState;

会做你想要的吗? 附注:如果您不更改变量,最好使用const而不是let