您好,欢迎访问一九零五行业门户网

操作render执行有哪些方法

这次给大家带来操作render执行有哪些方法,操作render执行的注意事项有哪些,下面就是实战案例,一起来看一下。
我们都知道render在组件实例化和存在期时都会被执行。实例化在componentwillmount执行完成后就会被执行,这个没什么好说的。在这里我们主要分析存在期组件更新时的执行。
存在期的方法包含:
- componentwillreceiveprops
- shouldcomponentupdate
- componentwillupdate
- render
- 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方法会被执行吗?
如图所示,当我们点击button时,子组件的render方法被执行了。可是从代码来看,组件绑定的onclick和text都没有发生改变啊,为何组件会更新呢?
如果在子组件的componentwillreceiveprops添加这个log:console.log(‘isequal', nextprops === this.props); 输出会是true还是false呢?
是的,你没有看错,输出的是false。这也是为什么子组件会更新了,因为属性值发生了变化,并不是说我们绑定在组件上的属性值。每次点击button时会触发state发生变化,进而整个组件重新render了,但这并不是我们想要的,因为这不必要的渲染会极其影响我们应用的性能。
在react中除了继承component创建组件之外,还有个purecomponent。通过该组件就可以避免这种情况。下面我们对代码做点修改再来看效果。修改如下:
class helloworldcomponent extends react.purecomponent
这次在点击button时发生了什么呢?
虽然componentwillreceiveprops依然会执行,但是这次组件没有重新render。
所以,我们对于无状态组件,我们应该尽量使用purecomponent,需要注意的是purecomponent只关注属性值,也就意味着对象和数组发生了变化是不会触发render的。
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
右侧带索引通讯录实现(附代码)
vue-ssr静态网站生成器vuepress使用详解
以上就是操作render执行有哪些方法的详细内容。
其它类似信息

推荐信息