💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 性能优化 在内部,React 使用一些聪明的技巧来最小化昂贵的 DOM 操作需求来更新 UI。对于许多应用,使用 React 可以生成一个快速的用户交互界面而不用做太多工作进行特别优化性能。闭关i平。有几种方式可以加速你的 React 应用。 ## 使用产品化构建 If you're benchmarking or experiencing performance problems in your React apps, make sure you're testing with the minified production build: 如果你在你的 React 应用中测试或者体验性能问题,确保你使用了压缩的产品化构建: 对于创建 React App,需要运行 npm run build 并遵循说明 对于单文件版本,我们提供了产品化之后的 .min.js 版本 对于 Browserify,你需要运行它,使用 NODE_EVN=production 对于 Webpack,需要添加这个到产品化配置文件的 plugins 中: * For Create React App, you need to run npm run build and follow the instructions. * For single-file builds, we offer production-ready .min.js versions. * For Browserify, you need to run it with NODE_ENV=production. * For Webpack, you need to add this to plugins in your production config: ~~~ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin() ~~~ 开发版本包括了额外的警告,可以在构建应用时提供帮助,但是由于额外的这些记录,会导致变慢。 ## 避免 调节 (Avoid Reconciliation ) React 构建和维护一个内部的渲染 UI 的表征。它包括你从组件中返回的 React 元素。这个表征使得 React 避免创建 DOM 节点和访问必要之外的现存的节点,因为这个可能慢于操作 JavaScript 对象。有时它被引用作为一个 “虚拟DOM”,但是它和 React Native 以同样方式运行。 当一个组件的 props 或者 state 改变,React 通过跟前一个渲染的元素对比最新的返回元素决定是否一个实际的 DOM 更新被需要。当它们不相等,React 则更新 DOM 。 在一些情况下,你的组件可以通过重写生命周期函数 shouldComponentUpdate 进行加速,它在重新渲染过程开始之前被触发。这个函数默认的实现返回 true ,使 React 来执行更新: ~~~ shouldComponentUpdate(nextProps, nextState) { return true; } ~~~ 如果你知道在一些情况下你的组件不需要更新,你可以从 shouldComponentUpdate 返回 false 来替代,以跳过整个渲染过程,包括在这个组件上及其下调用 render() 。 ## shouldComponentUpdate 运行 这是一个子树的组件。对于每个,SCU 表示 shouldComponentUpdate 的返回值,vDOMEq 表示是否渲染的 React 元素是等效的。最终,圆圈的颜色代表是否组件需要被调节或者不需要。 ![](https://box.kancloud.cn/cb7b5abf6b65e9dd428d2450b0f787d9_555x371.png) 由于在 C2 的子树 shouldComponentUpdate 返回 false,React 不会试图渲染 C2,因此甚至不用在 C4 和 C5 调用 shouldComponentUpdate 。 对于 C1 和 C3,shouldComponentUpdate 返回 true ,所以 React 必须向下检查它们。对于 C6 shouldComponentUpdate 返回 true,而且由于渲染的元素不相同,React 必须更新 DOM 。 The last interesting case is C8. React had to render this component, but since the React elements it returned were equal to the previously rendered ones, it didn't have to update the DOM. Note that React only had to do DOM mutations for C6, which was inevitable. For C8, it bailed out by comparing the rendered React elements, and for C2's subtree and C7, it didn't even have to compare the elements as we bailed out on shouldComponentUpdate, and render was not called.``