借用网上一个RN组件生命周期流程图来做说明,如下:
介绍组件生命周期前,先对此图做两点说明
1、ES6语法的引入,砍掉了getDefaultProps和getInitialState
- getDefaultProps 使用 static default={}的方式代替
- getInitialState 使用 state属性替代,初始化可以写在constructor里,也可以写成类属性
2、下一代RN版本,生命周期又有改变 详见https://github.com/facebook/react/issues/12152
- componentWillMount–使用componentDidMount代替
- componentWillUpdate–使用componentDidUpdate代替
- componentWillReceiveProps–使用一个新的方法:static getDerivedStateFromProps来代替
下面以一个demo对各个生命周期做详细介绍:
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Button
} from 'react-native';
e