我想了解最佳实践,以及我更新或修改数组中数组的方式是否正确。
当前,我处于这种状态:
州
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: bucket.blocks.map((block, i) => i === 0 ? {
...block,
messages: block.messages.map((message, i) => i === 0 ? {
...message,
replies: [...state.buckets[0].blocks[0].messages[0].replies, newReplies]
} : message)
} : block)
} : bucket)
};
有没有比这更好的方法来编辑数组中的数组了?
您是否建议重构此代码?
谢谢!
答案 0 :(得分:0)
如果您没有选择将状态规范化为易于处理的结构,则建议使用immer。
import produce from "immer";
...
case SEQUENCES.ADD_REPLY:
let newReplies = action.payload;
return produce(state, draft => {
draft.buckets[0].blocks[0].messages[0].replies.push(newReplies);
});
};