getInitialState和getDefaultProps
1. getInitialState函数的返回值用来初始化组件的this.state;
2. getInitialState只出现在装载过程,也就是说一个组件的整个生命周期过程中,这个函数只被调用一次;
3. getDefaultProps函数的返回值可以作为props的初始值;
4. 两个函数都只有在使用React.createClass方法创建组件类时才会用到:
const Sample = React.createClass({
getInitialState: function() {
return {foo: '返回值将作为this.state的初始值'};
},getDefaultProps: function() {
return {sampleProp: '作为props的初始值'}
}
})
5. React.createClass创建方法已经逐渐被Facebook官方废弃
6. 使用ES6时,在构造函数中通过this.state赋值完成状态初始化;通过给类属性(注意是类属性,而不是类的实例对象的属性)defaultProps赋值指定的props初始值:
class Sample extends React.Component{
constructor (props){
super(props);
this.state = {foo: '初始值'}
}
}
Sample.defaultProps = {
sampleProps: 0
}