Reputation: 4028
I am learning component lifecycle. As I know, getDeafaultProps() is called first when component is creating. I check the log, "Getting our default properties" is not print out. Why?
/*
* 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'));
Upvotes: 0
Views: 269
Reputation: 956
Make the getDefaultProps method static. It should work.
static getDefaultProps() {
console.log("Getting our default properties")
}
Upvotes: 0
Reputation: 104369
You need to use defaultProps
instead of getDefaultProps
, because you are using es6
, and you need to use it like this:
static defaultProps = {
p: console.log("Getting our default properties")
}
or define it outside of the class
in this way:
App.defaultProps = {
p: console.log("Getting our default properties")
}
Check this example:
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'/>
Upvotes: 0
Reputation: 31143
It should not be called since you use ES6 classes. See the documentation:
With functions and ES6 classes defaultProps is defined as a property on the component itself
With
createReactClass()
, you need to definegetDefaultProps()
as a function on the passed object
Upvotes: 1