【问题标题】:How to get objects by index immutable.js如何通过索引 immutable.js 获取对象
【发布时间】:2017-10-26 17:11:18
【问题描述】:

在 Immutable.js 中,如何通过索引从列表中获取对象并设置属性,然后更新整个列表。

状态是一个名为艺术家的对象数组。

[{ id: 1, selected: false}, { id: 2, selected: false}]

现在我希望在索引 0 处设置 selected = true

我试过了:

  const artistItem = state.get(action.payload.index).set({ selected: true });
  const artists = state.get('artists').set(action.payload.index, artistItem);

如何在不覆盖其他属性的情况下实现这一点?

【问题讨论】:

    标签: redux immutable.js


    【解决方案1】:

    如果你的状态真的看起来像

    [{ id: 1, selected: false}, { id: 2, selected: false}]
    

    相信你想用List#update:

    let state = Immutable.fromJS([
        {id: 1, selected: false},
        {id: 2, selected: false}
    ]);
    
    state = state.update(0, (artist) => artist.set('selected', true));
    console.log(state); // [{id: 1, selected: true}, {id: 2, selected: false}]
    
    // Note that this is equivalent to:
    state = state.set(0, state.get(0).set('selected'));
    

    但从您的代码看来,您的状态实际上看起来更像

    { artists: [{ id: 1, selected: false}, { id: 2, selected: false}] }
    

    如果是这种情况,您将需要使用Map#updateIn

    let state = Immutable.fromJS({
        artists: [
           {id: 1, selected: false},
           {id: 2, selected: false}
        ]
    });
    
    state = state.updateIn(['artists', 0], (artist) => artist.set('selected', true));
    console.log(state); //{artists: [{id: 1, selected: true}, {id: 2, selected: false}]
    
    // Note that this is equivalent to:
    state = state.set(
      'artists',
      state.get(artists).set(
        0,
        state.get(artists).get(0).set('selected', true)
    ));
    

    【讨论】:

      【解决方案2】:

      编辑

      ImmutableList.set() 返回另一个包含更改的列表。 这是修改项目的正确方法:

      const index = action.payload.index
      const newArtists = state.set(index, { ...state.get(index), selected: true });
      ...
      

      【讨论】:

      • 我应该提到我在对象中有其他属性。这将替换所有属性。我希望更新特定属性。我编辑了票
      • 结果如何
      • state.get(index) return undefined in { ...state.get(index), selected: true });
      • 因为该州可能没有这样的索引。先试试看
      • 索引确实在那里
      猜你喜欢
      • 2013-10-07
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多