如何替换现有数据(key/value 对)而不是通过不可变 js 附加到数组?

How to replace existing data (key/value pair) instead of appending to an array via immutable js?

我有一个基于 react/react-redux/redux saga/immutable js 构建的网络应用程序。 从 reducer,我有以下代码行。

const initialState = fromJS({ container: [] });
export default(state = initialState, action) => {
    switch(action.type) {
        case SOME_ACTION.FOO: {
            return state.set('container', state.set('container').push(fromJS({ key: action.name, data: action.address })));
            }

从 UI 组件我可以添加新条目作为 name: Peter, address: somewhere 作为 key/value 对然后 redux store 被正确更新。对于给定的代码,如果我添加相同的名称和相同的地址,它不会替换现有的 value 基于 key 而是它会继续附加到 container 数组或不可变上下文中的列表。

我尝试 state.update 纠正这种情况,但没有成功。我应该使用什么正确的语法来替换 container 数组中现有的 key/value 对条目?

[更新]

下面的代码块做了我需要的技巧。

return state.update('container', (container) => {
    const index = container.findIndex((x) => {
        return x.get('key') === `${action.name}`;
     });
     return index === -1 ? container.push(fromJS({ key: action.name, data: action.address })) : container;

由于这段代码,它一直附加到 container,因为您总是将对象推入数组:

state.set('container').push(fromJS({ key: action.name, data: action.address }))

如果您希望您的数据被覆盖,那么为什么不使用 {}

const initialState = fromJS({ container: {} });
export default(state = initialState, action) => {
switch(action.type) {
    case SOME_ACTION.FOO: {
        let info = { ...state.get('container').toJS(),{ action.name:action.address } }
        return state.set('container', info);

key 应该是一些 unique identifier 例如:user id