-
render
中只做与渲染有关的操作,只读取,不修改任何数据(临时变量除外)- 因为界面的更改是经常的,所以
render
是经常触发的 - 所以如果你有修改数据等操作,就会多次触发,使结果难以预料
- 比如你执行
setState
,那么setState
又触发render
,就会导致死循环
- 因为界面的更改是经常的,所以
-
随组件加载只执行一次的操作,放在
WillMount
或者DidMount
中- 比如远程取首页数据
(fetch)
,比如弹出提示框
- 比如远程取首页数据
-
记得在
WillUnmount
中销毁定时器和一些订阅事件
componentWillReceiveProps
组件接收到新的props
,会被调用
props
发生变化,使用componentWillReceiveProps
来处理(比如将变动同步给state
)
// props改变时调用
// 第一个参数:代表即将传入的新的props
componentWillReceiveProps(nextProps: Readonly<P>, nextContext: any): void {
this.setState({
isVisible: nextProps.show, // show为具体的props
});
}
生命周期函数
render() {
}
自己定义的函数
renderResult = () => {
}
import React,{Component} from 'react'
import {AppRegistry,StyleSheet,Text,View,Image,TouchableOpacity} from 'react-native'
class App extends Component {
state = {
likes: 0
};
onPress = () => {
const {likes} = this.state;
this.setState({
likes: likes + 1
});
};
render() {
return(
<View>
<TouchableOpacity onPress={this.onPress}>
<Image
style = {styles.image}
source = {{
uri: 'http://img.hb.aicdn.com/f16a90f723f26bc08104ca5623a509a695a4c00c1352-zYJ85p_fw658'
}}
/>
</TouchableOpacity>
<Text>{this.state.likes}</Text>
</View>
)
}
}
网友评论