简体   繁体   中英

What is the proper way to handle component's state in React?

I've seen people use the setState way:

this.setState( {enteredlocation: newLocation});

Currently I'm writing to the state like this:

this.state.id.push({"no" : length , "location": this.state.enteredlocation});

What is the proper way to update the state?

I'm also going to integrate Redux later on but for now, I'm trying to understand part by part.

Instead of this:

this.state.id.push({"no" : length , "location": this.state.enteredlocation});

...do:

this.setState({ 
  id: this.state.id.concat({
    "no": length, 
    "location": this.state.enteredlocation
  })
});

This will ensure that id is a new array reference, not the same reference with different contents.

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