简体   繁体   English

setState 一个数组和 object

[英]setState an array and object

How do you setState an object and an array at the same time after passing id and data to a function?在将 id 和数据传递给 function 后,如何同时设置状态 object 和数组? Because comment is not part of an array, I'm getting confused.因为评论不是数组的一部分,所以我很困惑。

this.state = {
      tasks: [
        { firstName: "boris", lastName: "Johnson", id: uuid() },
        { firstName: "Mary", lastName: "Whithaker", id: uuid() }
      ],
      comment: "This is a comment message"
    };

  updateTask(id, task, comment, additional) {
    const updatedProject = this.state.tasks.map(t => {
      if (t.id === id) {
        return {
          ...t,
          firstName: task,
          lastName: comment
        };
      }
      return t;
    });
    this.setState({ tasks: updatedProject, comment: additional });
  }

Your State is an object.您的 State 是 object。 In that object there are two fields, tasks and comment.在那个 object 中有两个字段,任务和评论。 Tasks is an array of objects, those objects have firstname, lastname and id fields. Tasks 是一个对象数组,这些对象具有 firstname、lastname 和 id 字段。 Comment is a string.评论是一个字符串。

When that code is doing setState at the end, it is creating a new object (see the {} ), and then giving it the updatedProject array for tasks , and then the additional string for comment .当该代码在最后执行setState时,它正在创建一个新的 object (请参阅{} ),然后将updatedProject数组用于tasks ,然后将additional字符串用于comment

That whole object is then set.然后设置整个 object。 The array and string are values of fields in that object.数组和字符串是 object 中字段的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM