2024-07-08
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
My English is limited and my skills are average. Please forgive me. Since I am not a translator, there are a lot of random translations. If you don't trust me, please read the original text~~
Original address:https://facebook.github.io/react/docs/advanced-performance.html
###Performance Optimization
Whenever developers choose to use React in real projects, they will first ask a question: Will using React make the project faster, more flexible, and easier to maintain? In addition, will the practice of re-rendering the interface every time the state data changes cause performance bottlenecks? Internally, React uses some subtle techniques to minimize the expensive DOM operations that cause each UI update to ensure performance.
####Avoid acting directly on the DOM
React implements a virtual DOM layer, which is used to map the browser's native DOM tree. This virtual DOM layer allows React to avoid directly operating the DOM, because the speed of directly operating the browser DOM is much lower than operating JavaScript objects. Whenever the properties or state of a component changes, React will construct a new virtual DOM in memory to compare with the old one to determine whether the browser's DOM tree needs to be updated, thus optimizing the performance loss of rendering the DOM as much as possible.
On top of this, react provides component lifecycle functions.shouldComponentUpdate
, the component will call this function before deciding to re-render (after the virtual DOM is compared and the final DOM is generated). This function gives the developer the authority to re-render. By default, this function returns directlytrue
, which means that the DOM update is triggered directly by default:
shouldComponentUpdate: function(nextProps, nextState) {
return true;
}
It is worth noting that react will call this function very frequently, so if you plan to implement the logic of this function yourself, please ensure performance as much as possible.
For example, if you have a chat application with multiple posts, and only one of them has changed, if you implementshouldComponentUpdate
, React will avoid re-rendering posts that haven't changed:
shouldComponentUpdate: function(nextProps, nextState) {
// TODO: return whether or not current chat thread is different to former one.
// 根据实际情况判断当前帖子的状态是否和之前不同
}
In short, React avoids expensive DOM operations as much as possible and allows developers to interfere with this behavior.
####shouldComponentUpdate in action
Here is an example of a component that contains sub-elements, as shown below: