【问题标题】:JavaScript | Spread operator update nested valueJavaScript |扩展运算符更新嵌套值
【发布时间】: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


【解决方案1】:

您无法使用this.state.posts[post.category] 访问您的数据。 posts数组对象中的数据。

您可以制作过滤器以在数组中查找您的类别对象并更改其帖子值。

onPostClick(post) {
    //CLONE YOUR DATA
    var postArray = this.state.posts;

    //FIND YOUR CATEGORY OBJECT IN ARRAY
    var categoryIndex = postArray.findIndex(function(obj){
        return obj.name === post.category;
    });

    //FIND YOUR POST AND CHANGE PUBLISHED VALUE
    postArray[categoryIndex].posts.forEach(function(item){
       if (item.id === post.id) {
           item.published = !item.published;
       } 
    });
    //SET TO STATE TO RERENDER
    this.setState({ posts: postArray});
}

如果你的州名是真的,这应该可以工作。

【讨论】:

  • 感谢您的回答!在我尝试这个之前,我只是想问一下。你为什么选择 for () 循环而不是 .forEach ?这是有原因的还是个人喜好?
  • @connormiotk96 我首先想到的。用 forEach 更新。
【解决方案2】:

只是补充一下,我们知道成功的方法有很多,也许你也想尝试这种方法..

onPostClick = post => {
    let published = this.state.data.map((item, i) => {
      item.posts.map((item_post, i) => {
        if (item_post.category === post.category) {
          item_post.published = !post.published;
        }
      });
    });
    this.setState({ ...this.state.data, published });
 };

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 2018-09-04
    • 2017-09-20
    • 2017-12-07
    • 2020-03-15
    • 2020-06-09
    • 2017-06-12
    • 2020-03-18
    • 1970-01-01
    相关资源
    最近更新 更多