簡體   English   中英

為什么在React Component構造函數中的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 ,因為您無法記錄varnew關鍵字。

如果要記錄父項的構造函數,可以嘗試:

console.log(super.constructor);

實際上, super()只是super.constructor()簡寫。

查看更多: https//developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Operators/super

super是一個關鍵字 ,你不能像變量一樣使用它。 MDN文檔中概述唯一允許使用super的方法:

超級([參數]); //調用父構造函數。

super.functionOnParent([參數]);

如果要打印父類,請改用console.log(super.constructor)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM