且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当父组件重新渲染时,使用 react-redux 的子组件的行为如何改变?

更新时间:2023-12-02 20:03:22

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.)