我正在尝试使用扩展运算符更新对象的嵌套值。这是我第一次使用它,我相信我已经接近实现我的最终目标了,但我似乎无法弄清楚接下来我真正需要做什么。
我有一个结构如下的数组:
[
{
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"
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
单击按钮时,我尝试更新已发布的值,当我使用 React 时,我需要设置状态。所以有人建议我使用扩展运算符进行更新。
onPostClick(post) {
post.pubished = !post.published;
this.setState({...this.state.posts[post.category], post})
}
Run Code Online (Sandbox Code Playgroud)
如果我注销结果,{...this.state.posts[post.category], post}我可以看到已发布的内容正在添加到形成的父级中:
{
name: "Category 1",
published: false,
posts: [
... …Run Code Online (Sandbox Code Playgroud)