I am trying to check if I set the same value to state as it has previously , does it re-render the component , or if it found that value is same then it will avoid the re-rendering.
最佳答案
类组件
调用setState
后,组件将无条件重新渲染。状态是否是相同的值并不重要,即通过 ===
比较的值:
this.setState(state => state); // re-render
或者通过浅对象比较的相同状态:
this.setState(state => ({...state})); // re-render
为了避免不必要的重新渲染,应该阻止组件更新,或者使用PureComponent
或shouldComponentUpdate
:
React.PureComponent is similar to React.Component. The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.
If your React component’s render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.
请注意,由于 React 中使用了虚拟 DOM,重新渲染并不一定会导致 DOM 重新渲染,并且可能具有可接受的性能。
功能组件
功能组件中的useState
Hook 提供了有状态类组件的替代方案。主要区别之一是,如果组件具有相同的值(即通过 ===
比较的值),则不会重新渲染组件:
const [state, setState] = useState({});
...
setState(state => state); // no re-render
否则组件将被重新渲染:
setState(state => ({...state})); // re-render
关于reactjs - 如果在状态中接收到相同的值,React 是否会重新渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52624612/