我的州有以下结构:
{ messages:
[
{ id: 1, comments: []}
]
}
我想在我的消息中添加一条新评论,我有消息ID,因此我可以轻松创建一个新状态,循环显示消息,并添加新评论,但它似乎并不是是正确的方式...
感谢您的帮助。
答案 0 :(得分:1)
试试这个:
var commentToAdd = { id: 1, comment: "text" };
this.setState({ messages: [...this.state.messages.map(i => i.id === commentToAdd.id ? { id: i.id, comments: [...i.comments, commentToAdd.comment] } : i) ] });
答案 1 :(得分:1)
最佳做法是将状态保持在规范化形状中,因此您将拥有以id为索引的对象而不是数组,而不是将注释存储在消息中,而只存储id。 对于你的例子,状态看起来像这样:
{
messages: {
byId: {
'1': { id: '1', comments: ['comment1'] },
...
},
allIds: ['1', ...]
},
comments: {
byId: {
'comment1': { id: 'comment1', ... },
...
},
allIds: ['comment1', ...]
}
}
在此类结构中,为了添加新评论,您必须更新comments
部分并在messages[id].comments
中添加新ID ...但现在更容易更新单个评价。
为了将对象规范化为这种形式,我建议normalizr。
有关在redux文档Normalizing State Shape
中规范化状态形状的更多信息