【RN基础02】React Native生命周期完全解析
2017-08-18 本文已影响31人
lltree
本文为转载文章,只因原作者写的太好了,读完瞬间理解,原网址:http://blog.csdn.net/tomasyb/article/details/71680342
生命周期图
20170511182906291.png20170511173234404.png
进入页面打印日志
加载阶段
点击我日志
20170511173547178.png点击让他死亡
--------componentWillUnmount组件移除前调用---------------
让他重生就回到加载阶段
20170511173443333.png项目源码
export default class LifeComponent extends Component {
//构造方法
constructor(props) {
super(props)
//定义state()
this.state = {
count: 0,
}
console.log('--------constructor构造方法---------------')
}
//组件装载前
componentWillMount() {
console.log('--------componentWillMount组件装载前---------------')
}
//组件装载后
componentDidMount() {
console.log('--------componentDidMount组件装载后---------------')
}
//组件跟新调用
componentWillReceiveProps(nextProps) {
console.log('--------componentWillReceiveProps组件跟新调用---------------')
}
//组件是否跟新
shouldComponentUpdate(nextProps, nextState) {
console.log('--------shouldComponentUpdate组件是否跟新---------------')
//默认返回true让他跟新
return true;
}
//组件跟新前调用
componentWillUpdate(nextProps, nextState) {
console.log('--------componentWillUpdate组件跟新前调用---------------')
}
//组件跟新后调用
componentDidUpdate(prevProps, prevState) {
console.log('--------componentDidUpdate组件跟新后调用---------------')
}
//组件移除前调用
componentWillUnmount() {
console.log('--------componentWillUnmount组件移除前调用---------------')
}
//渲染
render() {
console.log('--------render渲染---------------')
return (
<View>
<Text
style={{fontSize: 20, backgroundColor: 'red'}}
onPress={() => {
this.setState({
count: this.state.count + 1,
})
}}
>点击我</Text>
<Text style={{fontSize: 20, backgroundColor: 'blue'}}
>被点了{this.state.count}次</Text>
</View>
);
}
}
setup使用组件
import LifeComponent from '../common/LifeComponent'
export default class setup extends Component {
//模拟卸载
constructor(props) {
super(props);
this.state = ({
remove: false,
})
}
render() {
var view = this.state.remove?null:<LifeComponent/>;
var text = this.state.remove? '让他重生':'让他死亡';
return (
<View style={styles.container}>
<Text style={{fontSize:20}}
onPress={()=>{
this.setState({
remove:!this.state.remove,
})
}}
>{text}</Text>
{view}
</View>
);
}
}