简体   繁体   中英

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? 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. In that object there are two fields, tasks and comment. Tasks is an array of objects, those objects have firstname, lastname and id fields. 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 .

That whole object is then set. The array and string are values of fields in that object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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