React中的render什么时候执行过程

这篇文章主要介绍了React中的render什么时候执行过程,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

专注于为中小企业提供成都网站制作、网站设计服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业富民免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了成百上千企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

我们都知道Render在组件实例化和存在期时都会被执行。实例化在componentWillMount执行完成后就会被执行,这个没什么好说的。在这里我们主要分析存在期组件更新时的执行。

存在期的方法包含:

  1. - componentWillReceiveProps

  2. - shouldComponentUpdate

  3. - componentWillUpdate

  4. - render

  5. - componentDidUpdate

这些方法会在组件的状态或者属性发生发生变化时被执行,如果我们使用了Redux,那么就只有当属性发生变化时被执行。下面我们将从几个场景来分析属性的变化。

首先我们创建了HelloWorldComponent,代码如下所示:

import * as React from "react";
class HelloWorldComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  componentWillReceiveProps(nextProps) {
    console.log('hello world componentWillReceiveProps');
  }
  render() {
    console.log('hello world render');
    const { onClick, text } = this.props;
    return (
      <button onClick={onClick}>
        {text}
      </button>
    );
  }
}

HelloWorldComponent.propTypes = {
  onClick: React.PropTypes.func,
};

export default HelloWorldComponent;

AppComponent组件的代码如下:

class MyApp extends React.Component {
   constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
  }

  onClick() {
    console.log('button click');
    this.props.addNumber();
  }

  render() {
    return (
      <HelloWorld onClick={this.onClick} text="test"></HelloWorld>
    )
  }
}

const mapStateToProps = (state) => {
  return { count: state.count }
};

const mapDispatchToProps = {
  addNumber
};

export default connect(mapStateToProps, mapDispatchToProps)(MyApp);

这里我们使用了Redux,但是代码就不贴出来了,其中addNumber方法会每次点击时将count加1。

这个时候当我们点击button时,你觉得子组HelloWorldComponent的render方法会被执行吗?

React中的render什么时候执行过程 

如图所示,当我们点击button时,子组件的render方法被执行了。可是从代码来看,组件绑定的onClick和text都没有发生改变啊,为何组件会更新呢?

如果在子组件的componentWillReceiveProps添加这个log:console.log(‘isEqual', nextProps === this.props); 输出会是true还是false呢?

React中的render什么时候执行过程 

是的,你没有看错,输出的是false。这也是为什么子组件会更新了,因为属性值发生了变化,并不是说我们绑定在组件上的属性值。每次点击button时会触发state发生变化,进而整个组件重新render了,但这并不是我们想要的,因为这不必要的渲染会极其影响我们应用的性能。

在react中除了继承Component创建组件之外,还有个PureComponent。通过该组件就可以避免这种情况。下面我们对代码做点修改再来看效果。修改如下:

class HelloWorldComponent extends React.PureComponent

这次在点击button时发生了什么呢?

React中的render什么时候执行过程

虽然componentWillReceiveProps依然会执行,但是这次组件没有重新render。

所以,我们对于无状态组件,我们应该尽量使用PureComponent,需要注意的是PureComponent只关注属性值,也就意味着对象和数组发生了变化是不会触发render的。

感谢你能够认真阅读完这篇文章,希望小编分享的“React中的render什么时候执行过程”这篇文章对大家有帮助,同时也希望大家多多支持创新互联,关注创新互联行业资讯频道,更多相关知识等着你来学习!

当前文章:React中的render什么时候执行过程
网站网址:https://www.cdcxhl.com/article46/ppijeg.html

成都网站建设公司_创新互联,为您提供响应式网站小程序开发面包屑导航外贸网站建设移动网站建设网页设计公司

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

营销型网站建设