简体   繁体   中英

Cannot add object by using setState to Array in React js

Code

........
........
  state = {
    users: [],
    currentUser: '',
    currentAge: '',
  };

........
........

  onSubmitHandler = (e) => {
   
    const Person = {
      name: this.state.currentUser, //already assign in another function 
      age: this.state.currentAge,//already assign in another function 
    };


    this.setState({
      users: [...this.state.users, Person],
    });
  
  };

  render() {
    return (
      <div>
        <h1></h1>
        <form onSubmit={this.onSubmitHandler}>
          <label>
            Enter your name:
            <input type="text" onChange={this.onChangeNameHandler} />
          </label>
          <br />
          <label>
            Enter your Age:
            <input type="number" onChange={this.onChangeAgeHandler} />
          </label>
          <br />
          <input type="submit" />
        </form>

        <ul>
          {this.state.users.map((user) => {
            return <UserCard name={user.name} age={user.age} />;
          })}
        </ul>
      </div>
    );
  }
}

Error

Warning: Each child in a list should have a unique "key" prop.

Check the render method of `UserForm`. See https://reactjs.org/link/warning-keys for more information.
at UserCard (https://react-3agtbk.stackblitz.io/~/src/components/UserCard.js:7:1)
at UserForm (https://react-3agtbk.stackblitz.io/~/src/components/UserForm.js:10:9)
at div
at App

I'm trying to add the Person Object to the users array. However, when I try to console.log(this.state.users), It always shows [ ] . I did add preventDefault in my onSubmitHandler function which solve the issue. In my another project, I did not add onSubmitHandler which still works. Why it happening? Thanks in advance.

Two problems:

  1. Nothing in onSubmitHandler is preventing the default action of the submit, which is to submit the form to the server and replace the page entirely with the result from the server.

    You need to add a call to e.preventDefault() to prevent the default action of the submit.

  2. Your setState call should be using the callback version:

     this.setState(({users, currentUser, currentAge}) => { const Person = { name: currentUser, age: currentAge, }; return {users: [...users, Person]}; });

    That's best practice any time you're updating state based on existing state.

Also, as a side note, initially-capped variable names in JavaScript code are almost universally reserved for constructor functions. The overwhelmingly-standard convention for just a local variable referring to an object is to use initial-lower-case ( person , not Person ).

Putting all of that together:

onSubmitHandler = (e) => {
    e.preventDefault();

    this.setState(({users, currentUser, currentAge}) => {
        const person = {
            name: currentUser,
            age: currentAge,
        };
        return {users: [...users, person]};
    });
};

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