在React构造函数中调用super()做什么?
What does calling super() in a React constructor do?
从文档中学习React,遇到了这个例子:
class Square extends React.Component {
constructor() {
super();
this.state = {
value: null,
};
}
...
}
根据Mozilla, super允许你在构造函数中使用this
。是否有其他理由使用独立的super
(我知道super
允许您访问父类的方法),但与React有任何其他用例只是调用super()
本身?
super()
将调用其parent
类的constructor
。当你需要从父类访问一些变量时,这是必需的。
在React中,当你用props调用super
时,React会通过this.props
使props
在整个组件中可用。参见下面的示例2
不含super()
class A {
constructor() {
this.a = 'hello'
}
}
class B extends A {
constructor(){
console.log(this.a) //throws an error
}
}
console.log(new B())
with super()
class A {
constructor(props) {
this.props = props
}
}
class B extends A {
constructor(props) {
super(props)
console.log(this.props)
}
}
console.log(new B({title: 'hello world'}))
super()
只有在react组件中有构造函数时才会被调用。例如,下面的代码不需要super:
class App extends React.component {
render(){
return <div>Hello { this.props.world }</div>;
}
}
然而,如果我们有一个构造函数,那么super()
是强制性的:
class App extends React.component {
constructor(){
console.log(this) //Error: 'this' is not allowed before super()
}
}
this
不能在super()
之前被允许的原因是如果super()
没有被调用,this
是未初始化的。然而,即使我们不使用this
,我们也需要在构造函数中使用super()
,因为ES6 class constructors MUST call super if they are subclasses
。因此,只要有构造函数,就必须调用super()
。(但是子类不一定要有构造函数)
如果必须使用this.props
,则在构造函数内部调用super(props)
,例如:
class App extends React.component{
constructor(props){
super(props);
console.log(this.props); // prints out whatever is inside props
}
}
我希望我能说清楚。值得补充的是,super()
是超类构造函数的缩写,是继承的一个概念。
默认情况下,类Square
从它的超类React.Component
继承构造函数。
继承的构造函数可以通过声明一个新的constructor()
方法来重写。
如果目的是扩展而不是覆盖超类构造函数,那么必须使用super()
显式调用它。
在实现React.Component subclass
的构造函数时,应该在任何其他语句之前调用super(props)
。否则,this.props
将在构造函数中变为undefined
,这可能会导致错误。
在JavaScript中,super指的是父类的构造函数。
重要的是,在调用父构造函数之前,不能在构造函数中使用this。JavaScript不会让你:但是我们忘记了,如果在super()调用有机会设置this.name之前调用函数。所以this。name还没有定义!正如您所看到的,这样的代码很难理解。为了避免这样的陷阱,JavaScript强制规定,如果想在构造函数中使用this,必须先调用super。让父母做自己的事吧!这个限制也适用于定义为类的React组件:super();react不需要,但ES6子类
要使用this
关键字,我们应该在它之前使用super
关键字。为什么?super
用于调用父类的constructor
。
为什么我们需要调用父节点的constructor
呢?答案是初始化我们通过this
关键字引用的属性值。
- 这是什么 ==- javascript 运算符
- 我的单元测试选项是什么
- 全局变量和全局对象的属性之间有什么区别吗
- 打破承诺链的好方法是什么
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- Javascript中的空白是什么
- 是什么让一个“;Uncaught RangeError:超过了最大调用堆栈大小“;错误(Chrome,在其他浏览器中显示
- 在ember/handlers中使用value和valueBinding有什么区别
- 什么'在webpack外部设置中,reactDom和reactDom不同
- 在JavaScript中拆分日期字符串的更好方法是什么
- 为什么$.brower被弃用?还有什么更好的替代方案
- 什么是&&在没有if的行中的变量之间
- 将jQuery.ech()方法转换为本地JavaScript抽象的最佳方法是什么
- 处理浮点错误的最佳方法是什么
- DOM元素和angular元素之间的主要区别是什么
- javascript导入的最佳实践是什么
- 这两个关于 JavaScript 作用域链的例子有什么区别?
- 什么's本地node.js服务器和python简单http服务器之间的区别
- 在React构造函数中调用super()做什么?
- 在没有任何参数的情况下,super()做什么?