使用Redux推送或更新数组中的对象

时间:2019-03-08 08:52:05

标签: javascript redux react-redux

我想知道如何使用redux数组更新特定的数组或属性。

目前,我的状态是:

props1 : "props1",
props2 : "props2",
props3 : "props3",
buckets : [{
    bucketProps1 : "bucketProps1",
    bucketProps2 : "bucketProps2",
    bucketProps3 : "bucketProps3",
    blocks : [{
        blockProps1 : "blockProps1",
        blockProps2 : "blockProps2",
        blockProps3 : "blockProps3",
        messages : [{
            messageProps1 : "messageProps1",
            messageProps2 : "messageProps2",
            messageProps3 : "messageProps3",
            replies : [{ 
                repliesProps1 : "repliesProps1",
                repliesProps2 : "repliesProps2",
                repliesProps3 : "repliesProps3",
            },
            {...
            }],
        },
        {...
        }],
    },
    {...
    }],
},
{...
}]

我想在replies数组中添加一个答复:

reducer-sequences.js

case SEQUENCES.ADD_REPLY :

let newReplies = action.payload;

return {
...state,
buckets: state.buckets.map((bucket, i) => i === 0 ? {
        ...bucket,
        blocks: state.bucket.blocks.map((block, i) => i === 0 ? {
            ...block,
            messages: state.block.messages.map((message, i) => i === 0 ? {
                ...message,
                replies: [...state.buckets[0].blocks[0].messages[0].replies, newReplies]
            } : message)
        } : block)
    } : bucket)
};

但是我有这个错误:

  

TypeError:无法读取未定义的属性“块”

2 个答案:

答案 0 :(得分:1)

我认为不是这样做:

blocks: state.blocks.map

您应该这样做:

blocks: bucket.blocks

下一张地图也会发生相同的情况: 将其更改为:block.messages

答案 1 :(得分:0)

您应该执行以下操作: {...replies}不是...replies

但是,请尝试重构您的代码,以避免类似的复杂解决方案。