IOS React-native 生命周期

// ------------------- 生命周期 -------------------
// componentWillMount 最初的渲染之前调用一次,在React中,设置this.state会导致重新渲染,
// 但是componentWillMount设置this.state并不会导致render多次调用多次

//componentDidMount 在渲染结束后,调用一次

// componentWillReceiveProps 在component接收到新的参数前调用,
// 在这个方法中调动this.setState不会触发二次渲染,第一次渲染的时候不会调用这个方法

//shouldComponentUpdate
/*
boolean shouldComponentUpdate(
object nextProps, object nextState
)
在每次重新触发渲染之前调用,其中nextProps和nextState分别对应下一个状态的参数和状态对象。
可以在这个方法中发挥false来取消本次渲染
例如:
shouldComponentUpdate: function(nextProps,nextState) {
return nextProps.id !== this.props.id;
}
*/

//componentWillUpdate 在重新渲染之前调用
// ******** componentWillUpdate 这个方法里面不能调用this.setState(),否则会陷入死循环 ************

//componentDidUpdate 在渲染之后调用

//componentWillUnmount 在被删除之前调用

//为了更好的理解生命周期,重写整个类

class BasicProjectextends Component{
  getInitialState(){
    console.log("初始化:getInitialState");
    return {key:"点击屏幕任意位置"}
  }
  componentWillMount() {
    console.log("最初渲染:componentWillMount");
  }
  componentDidMount() {
    console.log("渲染结束:componentDidMount");
  }
  shouldComponentUpdate(nextProps,nextState){
    console.log("每次渲染之前:shouldComponentUpdate");
    return true;//返回false取消渲染
  }
  componentWillUpdate(nextProps,nextState){
    console.log("重新渲染之前:componentWillUpdate");
  }
  componentDidUpdate(prevProps,prevState){
    console.log("重新渲染之后:componentDidUpdate");
  }
  render() {
    return(
      <TouchableHighlight
        onPress={ () =>this.backgroundClick()}
        underlayColor='#ddd'
        style={styles.container}
      >
        <Textstyle={styles.welcome}>点击我</Text>
      </TouchableHighlight>
    );
  }
  backgroundClick(){
    this.setState({
      key:"设置了新的值"
    });
  }
}
运行效果

点击屏幕后

生命周期
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容