2017-04-11 75 views
0

我正在学习组件生命周期。据我所知,组件创建时,首先调用getDeafaultProps()。我检查日志,“获取我们的默认属性”不打印出来。为什么?为什么不调用console.log?

/* 
* 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()上的属性,你需要定义getDefaultProps()作为一个函数传递的对象上

+0

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

0

您需要使用defaultProps代替getDefaultProps,因为你正在使用es6,你需要使用它是这样的:

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方法静态。它应该工作。

static getDefaultProps() { 
    console.log("Getting our default properties") 
    } 
相关问题