在我的 react/redux 应用程序中,我使用类似这样的东西在我的 reducer 中设置状态:
state.set('search', myResults);
状态是一个不可变的 Map()
。当 toJS() 在其上运行时对象的格式(不再是不可变对象(immutable对象))如下所示:
{
results: { ..all results in here }
}
所以你会得到 state.search.results
。
这很好用,但是我有一个场景需要“推”到这张 map 的搜索部分。我在想 merge 会解决这个问题,但它似乎并没有像我想象的那样工作。我试过了:
state.mergeIn('search', singleResult);
还有
state.merge({ 'search': singleResult });
似乎都没有用。预期的结果是将单个结果插入状态 Map()
(而不是像 .set
那样覆盖它)。所以期望的结果最终看起来像这样:
{
results: { singleResult pushed or merged into here with other results }
}
我不确定如何使用 immutablejs 执行此操作,将不胜感激任何建议。谢谢!
最佳答案
您需要为此使用更新。合并不会在键中将数组连接在一起。
state.update('search', search => search.concat(singleResult));
还要注意,如果搜索包含一个普通的 JS 数组——那么数组本身仍然是一个可变数据结构。除非您使用 fromJS(),否则 Immutable.JS 不会对数据类型进行深度转换。
关于javascript - immutablejs (react/redux) , "push"进入不可变状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33813685/