美文网首页
React Native 生命周期

React Native 生命周期

作者: 努力生活的西鱼 | 来源:发表于2019-01-15 21:51 被阅读0次
ES6 React Native生命周期图
  • 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>
      )
  }
  
}

相关文章

网友评论

      本文标题:React Native 生命周期

      本文链接:https://www.haomeiwen.com/subject/uguudqtx.html