【问题标题】:Immutable JS and redux不可变的 JS 和 redux
【发布时间】:2018-10-15 12:55:27
【问题描述】:

我正在使用reduxImmutable JS。 我的state 是一个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 错误?

【问题讨论】:

    标签: javascript reactjs redux immutable.js


    【解决方案1】:

    你应该能够做到:

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

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

    【讨论】:

    • 啊,就是这样。应该是setIn。对于其他偶然发现这一点的人:确保不要将退货包裹在 {} 中,而是在 () 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多