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 https://reactjs.org/docs/react-api.html#reactpurecomponent or shouldComponentUpdate
:
React.PureComponent 与 React.Component 类似。区别
它们之间的区别是 React.Component 没有实现
shouldComponentUpdate(),但 React.PureComponent 使用
浅层 prop 和状态比较。
如果你的 React 组件的 render() 函数渲染相同的结果
给定相同的 props 和 state,你可以使用 React.PureComponent
在某些情况下性能提升。
请注意,由于 React 中使用了虚拟 DOM,重新渲染并不一定会导致 DOM 重新渲染,并且可能具有可接受的性能。
功能组件
useState
功能组件中的钩子提供了有状态类组件的替代方案。主要区别之一是,如果组件具有相同的值(即传递的值),则不会重新渲染===
比较:
const [state, setState] = useState({});
...
setState(state => state); // no re-render
否则组件会被重新渲染:
setState(state => ({...state})); // re-render
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)