【问题标题】:redux: set state in leaf node of large state treeredux:在大状态树的叶节点中设置状态
【发布时间】:2020-07-24 17:10:25
【问题描述】:

我有一个 Immutable 对象,其中包含其他 Immutable 对象,并且 redux 状态树设置为最顶层对象的实例:

records.js:

const TypeC = newRecord({
    content: null
})

const TypeB = newRecord({
    typeC: new TypeC;
})

export const TypeA = newRecord({
    typeB: new TypeB;
})

reducer.js:

import {
    TypeA,
} from './records';
import types from './types';

const applicationReducer = (state = new TypeA(), action) => {
    switch (action.type) {
    ...    
    }
    default:
        return state;
    }
};

我的问题是:如何编写reducer 代码来更改TypeC 中的content 字段?我试过类似的东西

CASE types.UPDATECONTENT: {
    return state.get('typeB').get('typeC').set('content', "new content")
}

但这似乎只返回我的状态树的 TypeC 段,当我需要从根开始的整个树时。

【问题讨论】:

    标签: redux immutable.js


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      state.get('typeB').get('typeC').set('content', "new content") 下树并修改 typeC 的属性“内容”。但是由于 immutable 是 immutable,它不会修改任何内容,它会返回一条具有更新值 (!) 的新记录。 state 和 'typeC' 之间的东西没有被触及。此外,set 返回新创建的记录,因此您可以用更新后的typeC 有效地覆盖state

      更新嵌套对象的一种简单方法是使用名为 <operation>In 的“深度持久更改”,例如setIn。它也负责创建更新的中间对象。

      TL/DR:

      CASE types.UPDATECONTENT: {
        return state.setIn(['typeB', 'typeC','content'], "new content");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-14
        • 2017-08-17
        • 1970-01-01
        • 1970-01-01
        • 2016-10-30
        • 2018-12-11
        • 1970-01-01
        • 2016-10-15
        相关资源
        最近更新 更多