What will happen if I use setState() function in constructor of a Class in ReactJS or React Native?

后端 未结 4 782
我寻月下人不归
我寻月下人不归 2020-11-28 07:58

Out of curiosity, I just wanna know what will happen if I use setState() function in constructor of a Class in React Native or ReactJS? Such as:



        
4条回答
  •  悲&欢浪女
    2020-11-28 08:36

    Error Message would be Uncaught TypeError: Cannot read property 'VARIABLE_NAME' of null

    Please see the following two jsfiddle snippets.

    Case 1) Working solution jsfiddle

    class Hello extends React.Component {
        constructor(props) {
          super(props);
    
          this.state = {
            name: 'world'
          } 
        }
    
      render() {
        return 
    {this.state.name}
    } } ReactDOM.render(, document.getElementById('container'));

    Case 2) Not working solution

    class Hello extends React.Component {
        constructor(props) {
          super(props);
    
          this.setState({
            name: 'hello'
          });
        }
    
      render() {
        return 
    {this.state.name}
    } } ReactDOM.render(, document.getElementById('container'));

    Conclusion:

    My rule of thumb, inside constructor uses this.state = {} directly, other places use this.setState({ });

提交回复
热议问题