react 性能优化

2020-08-17  本文已影响0人  一土二月鸟

减少render次数

import React from 'react';
import ReactDOM from 'react-dom';

class Index extends React.PureComponent {

  state = {
    data: {
      count: 1
    }
  }

  onClickBtn = () => {
    const data = this.state.data;
    data.count = 10;
    console.log(data);
    this.setState({
      data: data
    });
    this.forceUpdate();
  }

  render() {
    console.log('render...');
    return <>
      <p>{this.state.data.count}</p>
      <button onClick={this.onClickBtn}>add</button>
    </>;
  }

}

ReactDOM.render(<Index />, document.getElementById('root'));
import React from 'react';
import ReactDOM from 'react-dom';
import { Map } from 'immutable';

class Index extends React.Component { // 如果使用了shouldComponentUpdate,不推荐使用PureComponent,会被警告

  state = {
    data: Map({
      count: 1
    })
  }

  shouldComponentUpdate(nextProps, nextState) {
    if(this.state.data.equals(nextState.data)){ // 利用immutable的equals,可以快速比较复杂的数据是否发生了变化
      return false;
    } 
    return true;
  }

  onClickBtn = () => {
    this.setState({
      data: Map({
        count: 1
      })
    });
  }

  render() {
    console.log('render...');
    return <>
      <p>{this.state.data.get('count')}</p>
      <button onClick={this.onClickBtn}>add</button>
    </>;
  }

}

ReactDOM.render(<Index />, document.getElementById('root'));
import React, { Component } from "react";
import ReactDom from "react-dom";

const Child = (props) => {
  console.log("child render....");

  return <p>{props.t}</p>;
};

const ChildMemo = React.memo(Child);

class Index extends Component {

  state = {
    t: 1
  }

  clickBtn = () => {
    this.setState(state => ({
      t: state.t
    }))
  }

  render() {
    return (
      <>
        <button onClick={this.clickBtn} >click</button>
        <ChildMemo t={this.state.t} />
      </>
    );
  }
}

ReactDom.render(<Index />, document.getElementById("root"));
上一篇 下一篇

猜你喜欢

热点阅读