What's the difference between “super()” and “super(props)” in React when using es6 classes?

后端 未结 10 2098
不思量自难忘°
不思量自难忘° 2020-11-22 09:01

When is it important to pass props to super(), and why?

class MyComponent extends React.Component {
  constructor(props) {
    supe         


        
10条回答
  •  一向
    一向 (楼主)
    2020-11-22 09:29

    Here we won't get this in the constructor so it will return undefined, but we will be able to fetch this outside the constructor function

    class MyComponent extends React.Component {
      constructor() {
        console.log(this); // Reference Error i.e return undefined
      }
    
      render() {
        return 
    Hello {this.props.name}
    ; } }

    If we are using super(), then we can fetch the "this" variable inside the constructor as well

    class MyComponent extends React.Component {
      constructor() {
        super();
        console.log(this); // this logged to console
      }
    
      render() {
        return 
    Hello {this.props.name}
    ; } }

    So when we are using super(); we will be able to fetch this but this.props will be undefined in the constructor. But other than constructor, this.props will not return undefined.

    If we use super(props), then we can use this.props value inside the constructor as well

    Sophie Alpert's Answer

    If you want to use this.props in the constructor, you need to pass props to super. Otherwise, it doesn’t matter because React sets .props on the instance from the outside immediately after calling the constructor.

提交回复
热议问题