Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write and read component state in React?

Tags:

reactjs

I have MyComponent using setData() to write data in state and getData() to read the state. Is it best practice in React ? It works fine for me but not sure if what I am doing is the simplest possible way, please advice

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>                        
    );
  }
}
like image 549
irom Avatar asked May 01 '17 00:05

irom


1 Answers

There is absolutely no reason to do this. Just use this.state.data wherever you need to use it.

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

(source)

like image 171
JiN Avatar answered Oct 19 '22 17:10

JiN