【发布时间】:2019-04-26 16:35:51
【问题描述】:
我正在尝试使用扩展运算符更新对象的嵌套值。这是我第一次使用它,我相信我已经接近实现我的最终目标,但我似乎无法弄清楚我接下来真正需要做什么。
我有一个结构如下的数组:
[
{
name: "Category 1",
posts: [
{
id: 1,
published: false,
category: "Category 1"
},
{
id: 2,
published: true,
category: "Category 1"
}
]
},
{
name: "Category 2",
posts: [
{
id: 3,
published: true,
category: "Category 2"
},
{
id: 4,
published: true,
category: "Category 2"
}
]
}
]
单击按钮时,我正在尝试更新发布的值,并且在使用 React 时,我需要设置状态。所以有人建议我使用扩展运算符进行更新。
onPostClick(post) {
post.pubished = !post.published;
this.setState({...this.state.posts[post.category], post})
}
如果我注销{...this.state.posts[post.category], post} 的结果,我可以看到已发布的内容正在添加到形成的父级中:
{
name: "Category 1",
published: false,
posts: [
...
]
}
显然这不是预期的结果,我希望它更新posts 对象中的实际对象。
我尝试过类似this.setState({...this.state.posts[post.category].posts, post}) 的操作,但我收到一条消息说它未定义。
【问题讨论】:
-
onPostClick(post)- 什么是帖子格式,它是否包含完整数据以及 id / category 等? -
格式为
{ id: 1, category: 'Category 1', published: true } -
所以是的@Goran.it 它包含所有数据
标签: javascript reactjs ecmascript-6 spread-syntax