![](/img/trans.png)
[英]Why is `Promise.then` called twice in a React component but not the console.log?
[英]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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.