How to write and read component state in React?

I have MyComponent using setData () to write data in state and getData () to read state. Is this the best reagent practice? It works great for me, but not sure what I'm doing is the easiest way, please advise

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };

  }

  setData(){    
    this.setState({data:"123"});   
  }

  getData() {
    console.log(this.state.data); // 123 OK !!!   
  }

  componentDidMount() {    
    this.setData();  

  }
  componentDidUpdate() { 
    this.getData();
  }
  render() {
    return (                     
       <div>           
          {this.state.data} // 123 OK !!!
       </div>                        
    );
  }
}
+4
source share
1 answer

There is absolutely no reason for this. Just use this.state.data where you need to use it.

If you want to use state data in a child component, pass it as a support, and you can also pass a function to a child component that changes the state of the parent component.

+2
source

Source: https://habr.com/ru/post/1676040/


All Articles