为什么React组件中的console.log(super)会抛出一个错误
Why console.log(super) in React Component constructor throw an Error?
我想在我的InheritComponent
constructor
方法中安慰super
。但在chrome控制台,它抛出一个错误。为什么?
class BaseComponent extends React.Component{
static defaultProps = {
title: 'Learn React By Examples'
}
constructor(props) {
console.log(props);
super(props);
}
setTitle(title) {
document.title = title || this.props.title;
return document.title;
}
}
class InheritComponent extends BaseComponent{
state = {
title: ''
};
constructor(props) {
super(props);
//here throw an Error. Why? I want to console.log `super`
console.log(super);
}
componentDidMount() {
const title = this.setTitle('组件继承')
this.setState({title});
}
render() {
return <div>
<p>I inherit BaseComponent</p>
<p>current title is {this.state.title}</p>
</div>
}
}
ReactDOM.render(
<InheritComponent />,
document.body
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
以上是我的演示代码
原因很简单:super
是关键字,不是函数,也不是变量。super
和var
、new
关键字一样不能记录。
如果你想记录父类的构造函数,你可以试试:
console.log(super.constructor);
实际上,super()
只是super.constructor()
的简写。
查看更多:https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Operators/super
super
是一个关键字,你不能像使用变量一样使用它。唯一允许使用super的方法在MDN文档中列出:
超级((参数));//调用父构造函数
super.functionOnParent((参数));
如果你想打印父类,使用console.log(super.constructor)
。
相关文章:
- Webpack/Rect:遵循egghead.io教程,但出现错误:您可能需要一个合适的加载程序来处理此文件类型
- 是什么让一个“;Uncaught RangeError:超过了最大调用堆栈大小“;错误(Chrome,在其他浏览器中显示
- 从我的控制器返回一个不同于200的代码以触发ajax错误,这被认为是一种好的做法吗
- 预期响应包含一个对象,但在angular js中得到一个数组错误
- 错误:$injector:modulerr模块错误(我的第一个SPA应用程序)
- 一个ajax循环有两个输出错误innerHTML
- 在量角器中创建一个.txt错误输出文件是手动的,而不是控制台错误
- 我怎么能把一个错误当作未捕获的错误来记录呢
- 我需要一个jQuery函数来只工作在700px以上的屏幕大小,无法在我的代码中发现错误
- 在这个使用hasOwnProperty的对象扩展程序中有一个错误,I'我不确定那个bug是什么,也不确定这个扩展
- 从另一个JSAppleScript运行另一个JS AppleScript时出现权限错误
- 当张贴到数据库时,I'我得到了一个“;可以't在它们被发送错误之后设置报头”;
- javascript window.location在检查firebug时给了我一个错误的url路径
- 调试器;[错误]194:11:标识符是一个保留字
- new SharedWorker(“whatever.js”)返回一个错误
- 页面上的2个表单带有JS验证-其中一个抛出电子邮件验证错误
- JQuery关注上一个点击的输入错误
- 在一个函数中,我有一个未捕获的语法错误:意外的标记else
- 未捕获的引用错误——一个函数工作而另一个不起作用
- 图表API错误——[一个或多个参与者未能绘制()]