reactはレンダリングするコンポーネントを指定します。冗長なレンダリングを防ぐための3つの方法

方法1:ライフサイクル関数shouldComponentUpdate()を使用する

import React, {
    
     Component } from 'react'

class Foo extends Component {
    
    

  shouldComponentUpdate(nextProps, nextState) {
    
    
    //两个参数nextProps和nextState,表示下一次props和一次state的值
    //生命周期函数shouldComponentUpdate()默认返回ture,返回false时不会渲染render
    if (nextProps.name === this.props.name) {
    
    
      return false
    }
    return true
  }

  render() {
    
    
    console.log('Foo render')
    return null;
  }
}

export default class App extends Component {
    
    
  state = {
    
    
    count: 0
  }
  render() {
    
    
    return (
      <div>
        <button onClick={
    
    () => this.setState({
    
     count: this.state.count + 1 })}>Add</button>
        {
    
    /* 每次点击之后,state改变导致子组件也要重新进行不必要的渲染 */}
        <Foo name="Mike" />
      </div>
    );
  }
}



方法2:React.PureComponentを使用する

import React, {
    
     Component, PureComponent } from 'react'

class Foo extends PureComponent {
    
    
  //React.PureComponent 通过props和state的浅对比来实现 shouldComponentUpate()
  render() {
    
    
    console.log('Foo render')
    return null;
  }
}

export default class App extends Component {
    
    
  state = {
    
    
    count: 0,
  }
  render() {
    
    
    const {
    
     preson } = this.state
    return (
      <div>
        <button onClick={
    
    () => this.setState({
    
     count: this.state.count + 1 })}>Add</button>
        {
    
    /* 每次点击之后,state改变导致子组件也要重新进行不必要的渲染 */}
        <Foo name="Mike" />
      </div>
    );
  }
}



React.PureComponentは、ディープデータの不整合が原因で偽陰性の判断を生成する可能性があるため、shouldComponentUpdateの結果はfalseを返し、インターフェイスを更新できません。

方法3:react.memoを使用する(機能コンポーネント用)

import React, {
    
     Component, memo } from 'react'
//react.memo适用于函数式组件
//使用方式:只需将函数组件作为参数传入React.memo中
const Foo = memo(function Foo(props) {
    
    
  console.log('Foo render')
  return null;
});

export default class App extends Component {
    
    
  state = {
    
    
    count: 0,
  }
  render() {
    
    
    const {
    
     preson } = this.state
    return (
      <div>
        <button onClick={
    
    () => this.setState({
    
     count: this.state.count + 1 })}>Add</button>
        {
    
    /* 每次点击之后,state改变导致子组件也要重新进行不必要的渲染 */}
        <Foo name="Mike" />
      </div>
    );
  }
}



React.memoは、JSXマークアップでレンダリングされる精製されたコンポーネントMemoFuncComponentを返します。パラメータpropsとコンポーネントの状態状態が変化すると、Reactは前の状態とパラメータが次の状態とパラメータと同じかどうかをチェックします。同じ場合、コンポーネントはレンダリングされません。異なる場合は、コンポーネントが再レンダリングされます。

おすすめ

転載: blog.csdn.net/weixin_44745920/article/details/114959839