2017-04-11 8 views
0

私はコンポーネントのライフサイクルを学習しています。私が知っているように、getDeafaultProps()は、コンポーネントが作成されているときに最初に呼び出されます。私はログをチェックして、 "私たちのデフォルトプロパティを取得する"は表示されません。どうして?なぜconsole.logが呼び出されないのですか?

あなたは es6を使用しているため、 defaultProps代わりの getDefaultPropsを使用する必要があり、あなたはこのようにそれを使用する必要が
/* 
* A simple React component 
*/ 
class Application extends React.Component { 

    getDefaultProps() { 
    console.log("Getting our default properties") 
    } 
    componentWillMount() { 
    console.log("Before Mounting") 
    this.setState({count: 1}); 
    } 


    render() { 
    return <div> 
     <h1>{this.state.count}</h1> 

     <p> 
     More info <a href="https://github.com/bradleyboy/codepen-react" target="_blank">here</a>. 
     </p> 
    </div>; 
    } 
} 

/* 
* Render the above component into the div#app 
*/ 
React.render(<Application />, document.getElementById('app')); 

答えて

1

あなたはES6クラスを使用するので、それはと呼ばれるべきではありません。 documentationを参照してください:

機能とES6クラスのdefaultPropsでは、コンポーネント自体createReactClass()

のプロパティとして定義されている、あなたは、渡されたオブジェクト

+0

OMG !!!!!!!!!!!! – John

0

static defaultProps = { 
    p: console.log("Getting our default properties") 
} 

または、このようにclassの外にそれを定義します。

App.defaultProps = { 
    p: console.log("Getting our default properties") 
} 

チェックこの例:

class Application extends React.Component { 
 
    
 
    static defaultProps = { 
 
    p: console.log("Getting our default properties") 
 
    } 
 
    
 
    componentWillMount() { 
 
    console.log("Before Mounting") 
 
    this.setState({count: 1}); 
 
    } 
 

 

 
    render() { 
 
    return <div> 
 
     <h1>{this.state.count}</h1> 
 

 
     <p> 
 
     More info <a href="https://github.com/bradleyboy/codepen-react" target="_blank">here</a>. 
 
     </p> 
 
    </div>; 
 
    } 
 
} 
 

 
ReactDOM.render(<Application />, document.getElementById('app'));
<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> 
 

 
<div id='app'/>

0

の関数としてgetDefaultProps()を定義する必要がありますgetDefaultPropsメソッドを静的にします。それは動作するはずです。

static getDefaultProps() { 
    console.log("Getting our default properties") 
    } 
関連する問題