Is the constructor still needed in React with autobinding and property initializers

后端 未结 3 1891
悲&欢浪女
悲&欢浪女 2021-02-05 17:39

I am refactoring an es6 class based React component that uses the normal constructor, and then binds methods, and defines state/attributes within that constructor. Something lik

相关标签:
3条回答
  • You don't need to define a constructor explicitly , and then do super(props).You can access the props as in the example below. i.e. 'prop1'

    class MySpecialComponent extends React.Component {
        state = { 
        thing: true ,
       prop1:this.props.prop1
      }
      myAttribute = { amazing: false }
    
    
     myMethod = (e) => {
      this.setState({ thing: e.target.value })
    }
    
    
      render(){
      console.log(this.state.prop1);
       return(
           <div>Hi</div>
       );
    
       }
     }
    
    
     ReactDOM.render(<MySpecialComponent prop1={1}/> , mountNode);
    
    0 讨论(0)
  • 2021-02-05 18:18

    You don't need an explicitly defined constructor unless you need to reference the props in your initial state object.

    0 讨论(0)
  • 2021-02-05 18:19

    From my understanding, you don't need to type out a constructor at all when using class properties (as in your second code example). The accepted answer states that you do need one if you "need to reference the props in your initial state object," but if you're using said class properties, then you're probably using Babel to transpile it, in which case a constructor is used, it's just being done behind the scenes. Because of this, you don't need to add a constructor yourself, even if you are using props in state.

    See this aricle for better examples and a better explanation.

    0 讨论(0)
提交回复
热议问题