React is characterized by immutable data. When the data is changed, it does not actually change the value of the data. Instead, it regenerates the data into an object
Let’s do a +1 case
If this.state.n+=1 is used, the page data will not be refreshed because the UI has not updated this.state.n+=1; You should use this.setState({n: this.state.n + 1}) to generate a new object before calling setState triggers a refresh
class Son extends React.Component{
// Class component data initialization, super() must be written otherwise error
constructor(){
super(a)this.state={
n:0
};
};
add(){
// this.state.n+=1
this.setState({ n: this.state.n + 1 });
console.log(this.state.n) / / 0
};
Copy the code
This prints 0 because the new value overwrites the old value until the method is complete. SetState is an asynchronous method and does not change state immediately
Class components merge automatically, function components do not merge automatically
SetState automatically merges layer 1 properties, but not layer 2
N and m are level 1 properties; You just change the value of one n, and the other M stays the same if you don’t change it, so m stays the same
class Son extends React.Component{
constructor(){
super(a)this.state={
n:0
m:0
};
};
add(){
this.setState({
(state) = >{
const n = state.n+1
return {n:n}
}
})
};
Copy the code
Add a User object, and the attributes in the User object are second-level attributes
In this case, only the name of the second attribute will be changed. Age will not change, but the result age will be empty (age lost). Age will become undefined
class Son extends React.Component{
constructor(){
super(a)this.state={
n:0.m:0.user: {name:dong,
age:18}}; };changeUser(){
this.setState({
user: {name:"jack"}})};Copy the code
The solution
The solution is to use the extension operator to copy the original attributes and then change the attributes
changeUser(){
this.setState({
user: {... this.state.user,name:"jack"}})// Or this will copy this.state.user to the new object {}, which will then be assigned to user
const user = Object.assign({},this.state.user);
Copy the code