当父组件重新渲染时,使用 react-redux 的子组件的行为如何改变?
在 react-redux 的钩子文档我们被警告useSelector
与 connect
这对我来说是新闻.connect
是否会阻止正常子组件不会重新渲染的重新渲染?更具体地说,我问的是当父组件重新渲染而 store 和 props 保持不变时,以下三种场景的重新渲染行为的差异:
This is news to me. Does connect
prevent re-rendering where a normal child component would not re-render? More specifically, I'm asking about the difference in the re-rendering behavior of the below three scenarios when the parent component re-renders while the store and props remain unchanged:
- 子组件包含在
connect
HOC 中. - 行为为 1.,但注入状态被重构为
useSelector
. - 同 2.,但是
useSelector
和所有依赖它的东西都被删除了.
- The child component is wrapped in a
connect
HOC. - Behavior as 1., but injected state is refactored into
useSelector
. - As 2., but
useSelector
and everything dependent on it is removed.
connect
一直表现得像 React 的 PureComponent
的更复杂版本.具体来说,当连接组件的父组件渲染时,connect
只会重新渲染子组件,如果新的合并的 props"与之前相比发生了变化,其中 const mergeProps = { ...ownProps, ...stateProps, ...dispatchProps }
.
connect
has always acted like a more sophisticated version of React's PureComponent
. Specifically, when the parent of a connected component renders, connect
will only re-render the child component if the new "merged props" have changed from before, where const mergeProps = { ...ownProps, ...stateProps, ...dispatchProps }
.
因此,如果父组件传递与之前相同的 props,connect
包装器将阻止被包装的组件重新渲染.
So, if a parent component is passing down the same props as before, the connect
wrapper will prevent the wrapped component from re-rendering.
使用钩子,没有包装组件阻止该组件在其父组件传递相同的 props 时重新渲染.您需要将组件包装在 React.memo()
中才能实现.而且,事实上,这正是 connect
本身在版本 7 中的实现方式.
With the hooks, there is no wrapper component preventing this component from re-rendering if its parent is passing down the same props. You would need to wrap your component in React.memo()
to achieve that. And, in fact, that is exactly how connect
itself is implemented in version 7.
(来源:我是 Redux 维护者并编写了 React-Redux v7.)
(Source: I'm a Redux maintainer and wrote React-Redux v7.)