你不知道的React系列(三十六)性能优化

92 阅读1分钟

本文正在参加「金石计划」

  • 使用生产版本

    Create React App

    npm run build
    

    webpack

    module.exports = merge(common, {
      mode: "production",
    });
    
  • 虚拟化长列表

    react-windowreact-virtualized

  • shouldComponentUpdateReact.PureComponent

    shouldComponentUpdate 中返回 false 来跳过整个渲染过程。其包括该组件的 render 调用以及之后的操作

    class CounterButton extends React.Component {
      constructor(props) {
        super(props);
        this.state = {count: 1};
      }
    
      shouldComponentUpdate(nextProps, nextState) {
        if (this.props.color !== nextProps.color) {
          return true;
        }
        if (this.state.count !== nextState.count) {
          return true;
        }
        return false;
      }
    
      render() {
        return (
          <button
            color={this.props.color}
            onClick={() => this.setState(state => ({count: state.count + 1}))}>
            Count: {this.state.count}
          </button>
        );
      }
    }
    

    检查 propsstate 中所有的字段浅比较,使用 React.PureComponent

  • 不可变数据

    • concat
    this.setState(state => ({
        words: [...state.words, 'marklar'],
      }));
    
    function updateColorMap(colormap) {
      return {...colormap, right: 'blue'};
    }
    
    function updateColorMap(colormap) {
      return Object.assign({}, colormap, {right: 'blue'});
    }