博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
React16.3.0以后的生命周期(一) - 组件加载
阅读量:6939 次
发布时间:2019-06-27

本文共 1433 字,大约阅读时间需要 4 分钟。

组件加载

当组件被实例化并且插入Dom时所执行的方法,也会按照下的顺序依次执行。

  • constructor()

    构造方法。

    这个方法有两个目的:

    • 初始化一个本地state

      this.state = {color: 'red'};
      要避免将
      props参数直接赋值给
      state,
      this.state = {color: props.color}是不允许 的
    • 绑定方法。

      我们知道React Class中是不会继承this的,如果在class的方法中使用this,那么我们需要将this绑定到方法中。

      this.clickHandler = this.clickHandler.bind(this);
      绑定
      this,将需要
      super(props),否则会提示找不到
      this.

      示例:

      constructor(props) {  super(props);  this.state = {color: 'red'};  this.clickHandler = this.clickHandler.bind(this);}
  • static getDerivedStateFromProps()

    当本地state需要根据props来改变的时候可调用此方法。

    这个方法是在render()前会被执行,只要执行render()都会被在之前被触发。

    该方法有两个参数propsstate; 返回值为state对象, 不需要返回整体state,把需要改变的state返回即可。

    示例:

    static getDerivedStateFromProps(props, state) {  if(props.color !== state.color) {    return {color: props.color};  }}
  • render()

    这个方法是React组件中必须要提供的方法。当state或者props任一数据有更新时都会执行。

    需要注意当继承
    PureComponent时,不会对对象进行深度比较,也就是,不会根据对象内的对象变化时执行
    render().

    render()是一个纯函数,也就是不能在这个方法中有类似setState()这样的行为。

    返回的数据类型可以有:

    • nullStringNumberArrayBoolean
    • React elements
    • Fragment
    • Portal
    注意:不能返回
    undefined.

shouldComponentUpdate()返回false时,无论stateprops有没有变化,这个方法都不执行。

示例:

render() {  return (    
{this.state.color}
);}
  • componentDidMount()

    componentDidMount()方法是在组件加载完后立即执行,也就是当该组件相关的dom节点插入到dom树中时。该方法在组件生命中只执行一次。

    一般情况,我们会在这里setState()根据props的值,也可以从这里调用接口,获取服务端的数据,也可以在这里监听websocket、setInterval等操作。

    注意:一些监听需要在组件卸载时清理掉,否则会引起异常。

    示例:

    componentDidMount() {  this.setState({color: this.props.color});}

推荐阅读

转载地址:http://jksnl.baihongyu.com/

你可能感兴趣的文章
Git系列之一 --- git remote
查看>>
PHP 实现多服务器共享 SESSION 数据
查看>>
Linux系统信息查看命令大全
查看>>
Coursera机器学习编程作业Python实现(Andrew Ng)—— 1.2 Linear regression with multiple variables...
查看>>
Java源码分析-UUID
查看>>
Directx11教程(47) alpha blend(4)-雾的实现
查看>>
opengl 教程(12) 投影矩阵
查看>>
8086汇编——课堂笔记整理3
查看>>
Python批量修改文件名-后缀
查看>>
如何成为强大的程序员?(转)
查看>>
Codeforces Round #349 (Div. 2) C. Reberland Linguistics (DP)
查看>>
C语言中的字符串
查看>>
AngularJS 事件
查看>>
java中mkdir()和mkdirs()区别
查看>>
NIO系列——通道(Channel)
查看>>
NetCore 委托Func的使用
查看>>
《转》Xcode 6 正式版如何创建一个Empty Application
查看>>
公钥(Public Key)与私钥(Private Key)
查看>>
左右手坐标系与旋转正向
查看>>
hdu 2177 取(2堆)石子游戏(威佐夫博奕)
查看>>