react的生命周期
react的周期分为三个阶段
- 实例化阶段
getDefaultProps
当父组件没有传props时,取默认的props,此阶段在引入的时候就触发,即使没有实例化(最新版本的react没有此api,直接挂载在构造器上面。)
import React,{Component} from 'react'
class Test extends Component{
constructor(){
}
}
Test.defaultProps={
userName:'lili'
}
getInitialState
初始化内部的state
import React,{Component} from 'react'
class Test extends Component{
constructor(props){
super(props)
this.state={
initState:11
}
}
}
componenetWillMount
在render之前调用,实例化的时候调用,用于服务器渲染的时候用到,假如在这个阶段调用setState,之后走render方法。通常在contructor代替。
import React,{Component} from 'react'
class Test extends Component{
constructor(props){
}
willCompoentMount(){
}
}
2.更新阶段
componentWillReceiveProps
因父组件的更新props时而更新state时,会先执行这里面的方法,这里面的返回值为布尔值,一般常用于性能优化。
import React,{Component} from 'react'
class Test extends Component{
constructor(props){
super(props)
}
componentWillReceiveProps(nextProps){
//返回值为布尔值,为true会继续执行,为false则不会执行
return this.props.status!==nextProps.status
}
}