reactjs - 如果在状态中接收到相同的值,React 是否会重新渲染组件

标签 reactjs

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

为了避免不必要的重新渲染,应该阻止组件更新,或者使用PureComponentshouldComponentUpdate:

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/

相关文章:

reactjs - 我可以在 reducer 中发送一个 Action 吗?

javascript - 如何从经过 Firebase 身份验证的用户那里获取提供商访问 token ?

javascript - react 格式问题

javascript - 如何检测 React 中的 Esc 键按下以及如何处理

javascript - ReactJS + Gulp + Reactify + Browserify 元素类型无效 : expected a string but got: undefined

javascript - 检查两个数组是否包含相同的对象 - react componentDidUpdate

javascript - 如何在 react 中清除设置超时

html - 将纯 HTML 脚本转换为 jsx

reactjs - 如何安装react-toastr

reactjs - 在 Material-UI 中使用条件样式与 styled vs JSS