为什么使用immutableJS我的状态没有改变

Why does my state not change using immutableJS?

本文关键字:改变 状态 我的 immutableJS 为什么      更新时间:2023-09-26

我正试图将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少一个。但当我控制台日志状态时,它是一样的。我错过了什么?

当您调用state.set(...)时,它会返回一个新对象。原始state没有变化。我在你的摘录中更改了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