RN元件生命週期
阿新 • • 發佈:2018-12-14
在Android 和IOS我們都知道元件都有生命週期,RN的元件依舊不例外;
方法名 | 作用 | 呼叫次數 |
---|---|---|
constructor | 建構函式,初始化需要state | 1次 |
componentWillMount | 控制元件渲染前觸發 | 1次 |
render | 渲染控制元件的方法 | 多次 |
componentDidMount | 控制元件渲染後觸發 | 1次 |
componentWillReceiveProps | 元件接收到新的props被呼叫 | 多次 |
shouldComponentUpdate | 元件接收到新的props或state時呼叫 | 多次 |
componentWillUpdate | 元件接收到新的props或state時呼叫,shouldComponentUpdate返回為true時呼叫 | 多次 |
componentDidUpdate | 元件更新後呼叫 | 多次 |
componentWillUnmount | 解除安裝元件呼叫 | 1次 |
具體程式碼參考:
import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View} from 'react-native'; export default class LifecycleComponent extends Component { constructor(props) { super(props); console.log("====constructor:props:" + props); this.state = { count: 0, } } componentWillMount() { console.log("====componentWillMount"); } componentDidMount() { console.log("====componentDidMount"); } componentWillReceiveProps(nextProps) { console.log("====componentWillReceiveProps nextProps:" + nextProps); } shouldComponentUpdate(nextProps, nextState) { console.log("====shouldComponentUpdate:nextProps:" + nextProps + " nextState:" + nextState); return true; } componentWillUpdate() { console.log("====componentWillUpdate"); } componentDidUpdate() { console.log("====componentDidUpdate"); } componentWillUnmount() { console.log("====componentWillUnmount"); } render() { console.log("====render"); return <View> <Text onPress={()=> this.setState({ count:this.state.count+1, }) }>生命週期:{this.state.count}</Text> </View> } }
安裝後會自動提示,開啟連結會有安裝提示;