我知道通常道具中的任何更改或React组件的状态都会导致它重新渲染,但是当setState()
调用可以进行而不会导致重新渲染时会出现什么情况?
答案 0 :(得分:4)
When inheriting from plain React.Component
React will by default call render()
on the component when either the parent component re-renders or setState is called in the component.
However, if you implement shouldComponentUpdate() in your React component you will be able to short-circuit the update cycle. This is useful if you only have a limited number of props that are primitive values (string, number, bool) or when working with immutable data structures. Then you can simply do something like this:
shouldComponentUpdate(nextProps, nextState) {
return nextState.name !== this.state.name // Don't re-render if name is equal
}
The default implementation of shouldComponentUpdate() is
shouldComponentUpdate(nextProps, nextState) {
return true;
}
It is also possible to inherit from React.PureComponent which basically implements shallow comparison of your props and state.
I would recommend the following articles for a more in-depth answer: https://reactjs.org/docs/optimizing-performance.html#avoid-reconciliation and https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578 (Especially the section called (PureComponent and shouldComponentUpdate)
It is also useful to understand the difference between what happens when the render-function is called and what the reconciliation algorithm does to update the DOM. More on this here.