![](/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.