首页 > 解决方案 > redux:在大状态树的叶节点中设置状态

问题描述

我有一个包含其他不可变对象的不可变对象,并且 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 代码来更改contentTypeC 中的字段?我试过类似的东西

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

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

标签: reduximmutable.js

解决方案


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

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

TL/DR:

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

推荐阅读