组件优化性能

import React from "react";
class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      age: 66
    }
  }
  render() {
    console.log('Home被渲染了');
    return (
      <div>
        <p>Home</p>
        <p>{this.state.age}</p>
      </div>
    )
  }
}
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'xiebenyin'
    }
  }
  render() {
    console.log('App组件被渲染了');
    return (
      <div>
        <h1>App</h1>
        <p>{this.state.name}</p>
        <button onClick={() => this.btnClick()}>btn</button>
        <Home />
      </div>
    )
  }
  btnClick() {
    this.setState({
      name: 'xby'
    })
  }
}

export default App;
  • 修改  App 组件中的  this.state , Home 子组件也会被重新渲染

类组件优化性能

import React from "react";
class Home extends React.PureComponent { // 自己的 this.state 没有发生改变就不会重新渲染
  constructor(props) {
    super(props);
    this.state = {
      age: 66
    }
  }
  render() {
    console.log('Home被渲染了');
    return (
      <div>
        <p>Home</p>
        <p>{this.state.age}</p>
      </div>
    )
  }
}
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'xiebenyin'
    }
  }
  render() {
    console.log('App组件被渲染了');
    return (
      <div>
        <h1>App</h1>
        <p>{this.state.name}</p>
        <button onClick={() => this.btnClick()}>btn</button>
        <Home />
      </div>
    )
  }
  btnClick() {
    this.setState({
      name: 'xby'
    })
  }
}

export default App;
  • 使用  React.PureComponent  创建出来的组件,会自动进行优化,父组件的  this.state 发生改变不会重新渲染子组件

函数式组件 

import React from "react";
const MemoHome = React.memo(function (){ // 返回一个优化后的组件
  console.log('Home被渲染了');
  return (
    <div>Home</div>
  )
})

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'xiebenyin'
    }
  }
  render() {
    return (
      <div>
        <h1>App</h1>
        <p>{this.state.name}</p>
        <button onClick={() => this.btnClick()}>btn</button>
        <MemoHome />
      </div>
    )
  }
  btnClick() {
    this.setState({
      name: 'xby'
    })
  }
}

export default App;
  • 使用  React.memo 优化函数式组件,父组件自身的  this.state 发生改变,子组件不会重新渲染
posted @ 2021-12-16 22:10  霸哥yyds  阅读(84)  评论(0)    收藏  举报