About the state of React

background:

 constructor(props) {
    super(props);
    this.state = {
        _TagList: []
    }
}
onSelectCompany() {
        console.log("this.state._TagList:",this.state._TagList);//[]
        this.state._TagList.push("");
        console.log("this.state._TagList:",this.state._TagList);//[""]
        }

question: how is state modified? state is a variable, and any method that modifies a variable can modify it, right? If you are right, the change of state will not cause the page data to be updated. You can only call setState and then refresh it, right?

Mar.14,2021

first of all, let's make it clear that the modification of state, is not only to change the value of state itself, but also to cause the page to re-render, or modify state in order to cause the page to re-render.
this.state._TagList.push (''); this is not really modifying the state, because it will not trigger the page render,. You can't output the latest value in the render function at this time. The real modification of state must be a call to setState.
this.state._TagList is taking out the value of state, which is a normal variable. Any method that modifies a variable can modify it, which is also true, but this is not a modification of state.

with regard to changing the status correctly, the official document says three things:

1. Do not update status directly. Modifying the state, component directly does not re-render.

// 
this.state.name = 'React';
// 
this.setState({name: 'React'});

2. Status updates may be asynchronous. React may combine multiple setState changes into one to improve performance. This may lead to real state changes when the dependent this.state is not guaranteed to be the latest state, so don't rely on the current state to calculate the next state.

// 
this.setState({
  counter: this.state.counter + 1
});
// 
this.setState((prevState) => ({
  counter: prevState.counter + 1
}));

3. A status update merge is a shallow merge. When you call setState to modify the state of a component, you only need to pass in the changed state, rather than the entire state of the component.

// 
this.state = {
  name: 'React',
  age: 3
}
// 
this.setState({
  name: 'React Native'
});

state can only be modified through the setState method. The corresponding dom data will change.

Menu