首页 > 解决方案 > 不可变的 JS 和 redux

问题描述

我正在redux使用Immutable JS. Mystate是一个Immutable JS对象,类似于

const initialState = Immutable.fromJS({
    bar: 1
    foo: {
        bar: 'a',
        foo: 'b',
        foobar: [
            {
               ...
        ...
    ...

现在我有了减速器,通常我会这样做

export function foo(state = initialState, action) {
    switch (action.type) {
        case FOO:
            return {
                ...state,
                foo: {
                    ...state.foo,
                    bar: action.value
                }
            };
        ...

但是,现在我正在使用Immutable JS我需要做的

export function foo(state = initialState, action) {
    switch (action.type) {
        case FOO:
            return {
                ...state, // do I need to change something here too?
                foo: {
                    ...state.get('foo'), // this changed
                    bar: action.value
                }
            };
        ...

但是,这与我的商店混乱。我失去了一切,但是bar: action.value。好像...state.get('foo')不等于...state.foo

我该如何正确地做到这一点?还是我在这里用Immutable JS错了?

标签: javascriptreactjsreduximmutable.js

解决方案


你应该能够做到:

return state.set(['foo', 'bar'], value)

数组是对象嵌套属性中的路径,最后一个是新值。


推荐阅读