【问题标题】:Why does my state not change using immutableJS?为什么我的状态没有使用 immutableJS 改变?
【发布时间】:2016-05-17 04:27:03
【问题描述】:

我正在尝试将 immutableJS 添加到 Mern.io。当我尝试从我的帖子列表中删除帖子然后将其设置回我的状态时,状态不会更新。

case ActionTypes.DELETE_POST :
    const removeArray = state.get('posts')
              .filter((post) => post._id !== action.post._id)
    console.log(removeArray.length)
    state.set('posts', removeArray)
    console.log(state)
    return state;

在这个例子中,如果我有一个 5 的数组,我应该能够将其过滤掉,然后使用新数组再次设置“posts”。我不明白的是我可以从数组中删除对象,removeArray 将比 state.posts 少一个。但是当我控制台日志状态时它是一样的。我错过了什么?

【问题讨论】:

    标签: javascript reactjs redux immutable.js


    【解决方案1】:

    当您调用state.set(...) 时,它会返回一个新对象。原来的state 不变。我在您的 sn-p 中更改了 3 行:

    case ActionTypes.DELETE_POST :
        const removeArray = state.get('posts')
                  .filter((post) => post._id !== action.post._id)
        console.log(removeArray.length)
        const newState = state.set('posts', removeArray) // assign to another variable
        console.log(newState) // and log here
        return newState; // and you'll probably want to return the new state
    

    【讨论】:

    • 切换到state.update('posts', ...)也有意义
    • @zerkms 感谢您更新 sn-p!
    • @ffffranky 谢谢这真的把事情搞清楚了。每次你为它的一部分设置一个新值时,一个不可变对象都会保存一个历史记录。
    • 有人可以投票支持我的问题,因为回答很有帮助,我觉得很好地澄清了问题。
    猜你喜欢
    • 1970-01-01
    • 2021-11-25
    • 2020-08-21
    • 1970-01-01
    • 2018-12-29
    • 2017-01-04
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多