React之性能优化

版权声明: https://blog.csdn.net/Her_smile/article/details/81411930
  • 第一是当我们构建生产环境的时候,打包的时候需要去掉开发环境里面的react Waring,这个在开发的时候很有用但是在生产环境中不需要,因此需要去除。像webpack构建的时候,我们需要加入一些plugin,如下
new webpack.DefinePlugin({
  'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.UglifyJsPlugin()
  • 当我们在渲染的时候包括了很长很长的列表数据,表格数据等,我们可以使用一个库React Virtualized,这种技术只在任何给定的时间内呈现您的行的一小部分,并且可以显著减少重新呈现组件所需的时间以及创建的DOM节点的数量
  • 改善shouldComponentUpdate,默认情况下shouldComponentUpdate是返回true也就是不管我们的props或者state有没有改变,他都会返回true,最终导致React执行更新。一种是我们手动改变shouldComponentUpdate在里面对数据进行手动比较,然后返回结果,一种是不再继承React.Component,而是继承React.PureComponent,React.Component默认是没有继承shouldComponentUpdate的,而React.PureComponent有继承,如果我们的应用数据比较简单,便可以继承React.PureComponent,而不用我们手动去写,但是React.PureComponent比较的是前后的引用是否相等,而不是具体的数据结构是否相等,例如我们的state: { arr: [1, 2, 3]}, 此时往arr里面添加一个, state: {arr: [1, 2, 3, 4]},此时React.PureComponent的shouldComponentUpdate是会返回fasle的,因为都是一个数组,这个时候,更新的时候,使用扩展运算符,或者Object.assign(),来改变引用,React.PureComponent的shouldComponentUpdate就起作用了,进而触发render,或者我们重写shouldComponentUpdate来手动比较。

猜你喜欢

转载自blog.csdn.net/Her_smile/article/details/81411930