React中constructor(){}

来源:互联网 发布:好伙伴物流软件 编辑:程序博客网 时间:2024/05/27 16:43

当你在React class中需要设置state的初始值或者绑定事件时

需要加上constructor(){}

[javascript] view plain copy
  1. constructor() {  
  2.         this.state = {searchStr: ''};  
  3.         this.handleChange = this.handleChange.bind(this);  
  4.     }  

但当你运行时,是会出现问题的。



提示没有在this之前加上super()

其实就是少了super(),导致了this的 Reference Error

[objc] view plain copy
  1. class MyComponent extends React.Component {  
  2.   constructor() {  
  3.     console.log(this); // Reference Error  
  4.   }  
  5.   
  6.   render() {  
  7.     return <div>Hello {this.props.name}</div>;  
  8.   }  
  9. }  


个人理解super()是继承了整个类的一个引用(希望知道的帮忙解释下)

正确的姿势应该是这样

[javascript] view plain copy
  1. constructor() {  
  2.         super();  
  3.         this.state = {searchStr: ''};  
  4.         this.handleChange = this.handleChange.bind(this);  
  5.     }  

那么React的官方例子中都是加上了props作为参数

[javascript] view plain copy
  1. constructor(props) {  
  2.         super(props);  
  3.         this.state = {searchStr: ''};  
  4.         this.handleChange = this.handleChange.bind(this);  
  5.     }  


那它们的区别在哪儿呢

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

借用下stackoverflow上的解释

There is only one reason when one needs to pass props to super():

When you want to access this.props in constructor.

(Which is probably redundant since you already have a reference to it.)


意思是说
只有一个理由需要传递props作为super()的参数,那就是你需要在构造函数内使用this.props

那官方提供学习的例子中都是写成super(props),所以说写成super(props)是完全没问题的,也建议就直接这样写

原创粉丝点击