zoukankan      html  css  js  c++  java
  • React Native填坑之旅--组件生命周期

    这次我们来填React Native生命周期的坑。这一点非常重要,需要有一个清晰的认识。如果你了解Android或者iOS的话,你会非常熟悉我们今天要说的的内容。

    基本上一个React Native的组件会经历三个阶段最终渲染在界面上,他们分别是:开始渲染、更新、卸载。

    开始渲染:

    componentWillMount

    componentWillMount(): void
    

    组件开始渲染的时候调用这个方法

    componentDidMount

    componentDidMount(): void
    

    组件的渲染完成之后调用这个方法。子组件的componentDidMount方法会在父组件的前面调用。componentWillMountcomponentDidMount方法之前调用,这个时候组件还没有渲染完成。所以在componentWillMount里调用setState方法会立刻在render方法里看到更新了的数据。

    更新

    componentWillReceiveProps

    componentWillReceiveProps(nextProps: Object): void
    

    当有新的Props发送给组件的时候,这个方法被触发。最开始的render并不会调用这个方法! 使用这个方法可以在更新state,render方法被调用之前修改组件的props。在这个方法里可以使用this.props来使用旧的props。在这个方法里调用setState方法不会触发额外的render。

    例如:

    componentWillReceiveProps(nextProps) {
      this.setState({
        currentCategory: nextProps.category !== this.props.category
                          ? nextProps.category
                          : this.props.category
      });
    }
    

    shouldComponentUpdate

    shouldComponentUpdate(nextProps: Object, nextState: Object): void
    

    当收到新的props或者state的时候触发这个方法。默认情况下shouldComponentUpdate一直返回true。这个方法在第一次render的时候不会调用。当你确定props和state被设置为新的值以后不需要组件更新的时候返回false。之后render方法在本次的更新中就会被直接跳过,componentWillUpdatecomponentDidUpdate两个方法也不会被调用。

    componentWillUpdate

    componentWillUpdate(nextProps: Object, nextState: Object): void
    

    在props或者state更新之后立即调用这个方法。这个方法不会在第一次render的时候调用。

    render

    render(): ReactElement<{}>
    

    render方法被调用的时候,组件会根据新的this.propsthis.state绘制。render方法应该是一个纯方法。也就是说,它不修改组件的state,并且每次调用都返回相同的结果。当然,这个需要开发者来保证。

    componentDidUpdate

    componentDidUpdate(prevProps: Object, prevState: Object): void
    

    每次组件更新之后调用。第一次render的时候不会调用。

    卸载

    componentWillUnmount(): void
    

    组件被卸载之后调用。可以在这个方法里执行一些清理操作。

  • 相关阅读:
    PHP编程中一些时间和日期代码调用的实例
    想不显示织梦栏目列表页缩略图就是不显示默认缩略图怎么办
    织梦dede文章增加HTML自定义字段字符被过滤问题
    Dedecms友情链接/uploads/fli<x>nk/不显示正确的图片路径错误
    Dedecms教程:整站调用购物车订单数量简单解决办法
    织梦DedeCMS模板常用的内容统计sql标签代码
    DEDECMS首页loop调用留言本带用户头像的方法
    Python 序列、列表(List)、元组(Tuple)
    Python 字符串常用函数
    Python 运算符
  • 原文地址:https://www.cnblogs.com/sunshine-anycall/p/6089077.html
Copyright © 2011-2022 走看看