每一个新的东西都会有自己的生命周期,在React-Native(以下简称RN)中组件的生命周期有时候如何呢?
下面主要讲解一下在RN组件的生命周期。对于RN组件的生命周期主要分为三个阶段。(运行---更新---卸载)
常见的函数为:
/**
* 组件生命周期
*
* 运行----
* getDefaultProps (ES6 static defaultProps) 主要设置默认属性
* getInitialState(ES6 constructor(props)) 初始化函数
* componentWillMount
* render 组件渲染
* componentDidMount 组件渲染完成
*
* 更新----
* componentWillReceiveProps 属性发生改变
* shouldComponentUpdate 是否进行组件渲染
* componentWillUpdate 改变之后渲染 前
* render 组件属性发生改变之后渲染
* componentDidUpdate 改变之后渲染 后
*
* 卸载----
* componentWillUnmount 卸载 (资源回收 释放)
*/
简单举个例子如下:(通过远程调试RN程序便可以看到相应的log输出)
export default class Lifestyle extends Component{ constructor(props){ super(props); console.log("---constructor--") this.state={ clk_count:0 } } componentWillMount(){ //装载之前 console.log("---componentWillMount--") } componentDidMount(){ //装载之后 console.log("---componentDidMount--") } componentWillReceiveProps(nextProps){ //属性改变 console.log("---componentWillReceiveProps--") } shouldComponentUpdate(nextProps,nextState){ //是否更新 console.log("---shouldComponentUpdate--") return true; } componentWillUpdate(nextProps,nextState){ //更新前 console.log("---componentWillUpdate--") } componentDidUpdate(nextProps,nextState){ //更新后 console.log("---componentDidUpdate--") } componentWillUnmount(){ //卸载 console.log("---componentWillUnmount--") } render(){ console.log("---render--") return( <View> <Text onPress={()=>{ this.setState({ clk_count:this.state.clk_count+1, }) }} >hello 点击</Text> <Text>点击了{this.state.clk_count}次</Text> </View> ) } }