天行健, 君子以自强不息
Sunny's Blog
Title

React Optimizing Performance

这里面主要记录一些react写法上的优化点

1)Virtualize Long Lists

针对react中过长的list做的插件:https://bvaughn.github.io/react-virtualized/#/components/List

2)shouldComponentUpdate

If you know that in some situations your component doesn’t need to update, you can return false from shouldComponentUpdate instead, to skip the whole rendering process, including calling render() on this component and below.

React.PureComponent

有一个参考文档: https://60devs.com/pure-component-in-react.html

如果将Component换成PureComponent确实可以大大提升react的代码性能,这里边会自动进行shouldComponentUpdate的检测并减少这部分代码量,在props和state不发生变化的情况下,不会产生render。有一个问题是,这里边的对比只是一个shallow comparison,所以某些情况下props或state发生了变化但是没有re-render

                    //关键是this.setState({words: words});要写成this.setState(prevState => ({ words: [...prevState.words, 'marklar'] }));
                    //生成一个新的数组赋值给words而不是用原有的引用。

                    class ListOfWords extends React.PureComponent {
                      render() {
                        return <div>{this.props.words.join(',')}</div>;
                      }
                    }

                    class WordAdder extends React.Component {
                      constructor(props) {
                        super(props);
                        this.state = {
                          words: ['marklar']
                        };
                        this.handleClick = this.handleClick.bind(this);
                      }

                      handleClick() {
                        // This section is bad style and causes a bug
                        const words = this.state.words;
                        words.push('marklar');
                        this.setState({words: words});
                      }

                      render() {
                        return (
                          <div>
                            <button onClick={this.handleClick} />
                            <ListOfWords words={this.state.words} />
                          </div>
                        );
                      }
                    }
            
地势坤,君子以厚德载物