关于React ES6 class constructor su

2017-10-22  本文已影响0人  风起云帆

当我们在写React时候 会用到ES6中的class语法 ,比较常见的情况如下:

class MyClass extends React.Component{ constructor(){ super() }}

这里有两个问题:

  1. 是否有必要在constructor中调用super()函数?
  2. 调用super()和super(props)有何区别 ?

解答 Q1:
Always call super() if you have a constructor and don't worry about it if you don't have a constructor

只有当你有一个constructor时候调用super()才是必须的 看代码:

class MyClass extends React.component{ 
    render(){ 
        return <div>Hello {this.props.world}</div> 
  }
}

上述代码完全符合规定所以你其实并没有必要去为你创建的每个React Component 调用super()话分两头 如果你的代码中有constructor你就必须调用super()

class MyClass extends React.component { 
    constructor(){ 
        console.log(this) //Error: 'this' is not allowed before           
    super() 
  }
}

出现上述错误的原因是 super() 未被调用之前 this 还未被初始化 (uninitialized) 了解更多或许c聪明的你会想着 使用一个空的constructor从而摆脱super()

class MyClass extends React.component {
    constructor(){} // Error: missing super() call in constructor
}

ES6的 class 的constructors如果属于子类就必须调用super()方法,所以一旦你的代码有constructor,你就必须调用用 super()

解答Q 2:

Call super(props) only if you want to access this.props inside the constructor. React automatically set it for you if you want to access it anywhere else.

假使你想获取到constructor中的this.props你就必须调用super(props),然后React就会自动为你自动为你配置好它 以便你可以在随便什么地方调用它,看一下使用super()
和 super(props)的不同 :

class MyClass extends React.component{     
   constructor(props){
        super(); 
        console.log(this.props); // this.props is undefined
   }
}

当使用super(props)时,你可以从constructor中获取到this.props

class MyClass extends React.component{ 
    constructor(props){ 
        super(props); 
        console.log(this.props); // prints out whatever is inside props
   }
}

当然还有一点 当你想在其他地方使用它时 也没有必要将props传递到constructor中 React会自动为你设置好它 了解更多
class MyClass extends React.component{ render(){ // There is no need to call super(props) or even having a constructor // this.props is automatically set for you by React // not just in render but another where else other than the constructor console.log(this.props); // it works! }}

总之 需要绑定 this.方法或是需要在 constructor 使用操作 props 定义 state,就需要 constructor ,否则 例如在其他方法中(如 render())使用 this.props 则没必要要使用constructor

原文链接:http://cheng.logdown.com/posts/2016/03/26/683329

上一篇 下一篇

猜你喜欢

热点阅读