【问题标题】:Push or update an object in array in array with redux使用 redux 推送或更新数组中的对象
【发布时间】:2019-07-30 06:36:07
【问题描述】:

我想知道如何使用 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",
            },
            {...
            }],
        },
        {...
        }],
    },
    {...
    }],
},
{...
}]

我想在回复数组中添加回复:

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: 无法读取未定义的属性“块”

【问题讨论】:

    标签: javascript redux react-redux


    【解决方案1】:

    我认为不是这样做:

    blocks: state.blocks.map
    

    你应该这样做:

    blocks: bucket.blocks
    

    下一张地图也会发生同样的事情: 改成:block.messages

    【讨论】:

      【解决方案2】:

      你应该做这样的事情: {...replies} 不是 ...replies

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-12
        • 2020-10-11
        相关资源
        最近更新 更多