React中函数组件和类组件解决无效渲染

了解什么是无效渲染

组件是构成React视图的一个基本单元。有些组件会有自己本地的状态(state), 当它们的值由于用户的操作而发生改变时,组件就会重新渲染。在一个React应用中,一个组件可能会被频繁地进行渲染。这些渲染虽然有一小部分是必须的,不过大多数都是无用的,它们的存在会大大降低我们应用的性能。

即简单理解为,无效渲染就是一些状态值的改变我们没有必要也发生渲染,例如我们程序中设置的值前后相等的,但是执行了setState后还是会发生渲染,render函数即会被调用。

测试一下:

import React, { Component } from 'react'

export default class App extends Component {
  state={
    count:1
  }
  fn=function(){
    this.state.count=2
    this.setState(this.state)
  }
  render() {
    console.log(111111);
    return (
      <div>
        {this.state.count}<br/>  
        <button onClick={this.fn.bind(this)}>点击修改count</button>
      </div>
    )
  }
}

当第一次点击按钮以后,从新渲染并将count的值设为了2;但是当变为2了以后再点击按钮就是2赋给2,这对程序来说是没有意义的从新渲染,即推出了响应的解决办法。

1、在类组件中解决无效渲染

1.1利用shouldComponentUpdate

这是React类组件中的一个生命周期钩子,它的触发事件是在componentWillUpdata之前,它有返回值是Boolean值true或者false。当为true时,才会往下执行componentWillUpdata和componentDidUpdata,实现组件从新渲染。当返回值为false时组件就会被卡死在这里,永远不会从新渲染组件。

利用这一特性,我们可以在shouldComponentUpdate钩子中做逻辑判断,判断什么时候从新渲染页面。

改进上面代码:

import React, { Component } from 'react'

export default class App extends Component {
  state={
    count:1
  }
  fn=function(){
     this.setState({count:2})
  }
  render() {
    console.log(111111);
    return (
      <div>
        {this.state.count}<br/>  
        <button onClick={this.fn.bind(this)}>点击修改count</button>
      </div>
    )
  }

//nextProps: 组件将会接收的下一个参数props
//nextState: 组件的下一个状态state
  shouldComponentUpdate(nextProps, nextState){
    if (this.state.count===nextState.count) {
      return false
    }
    return true
  }
}

 1.2、Pure Component

这个方法是在15.5版本的时候引入的,将我们的我们只需要在创建类的时候继承PureComponent,如:

 在继承PureComponent后,React在进行组件更新时,如果发现这个组件是一个PureComponent,它会将组件现在的state和props和其下一个state和props进行浅比较,如果它们的值没有变化,就不会进行更新。

2、函数组件中解决无效渲染

memo

React.memo()是React v16.6引进来的新属性。它的作用和React.PureComponent类似,是用来控制函数组件的重新渲染的。React.memo(...)其实就是函数组件的React.PureComponent。

用法也非常简单:

import React from 'react'
let myfn=function box2() {

  return (
    <div>
        box2
    </div>
  )
}
myfn=React.memo(myfn)//React.memo会返回一个纯化的组件
export default myfn

猜你喜欢

转载自blog.csdn.net/m0_59345890/article/details/127304280