问题
At react-redux's hooks documentation we are warned that useSelector "does not prevent the component from re-rendering due to its parent re-rendering, even if the component's props did not change," unlike connect
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:
- The child component is wrapped in a
connectHOC. - Behavior as 1., but injected state is refactored into
useSelector. - As 2., but
useSelectorand everything dependent on it is removed.
回答1:
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 }.
So, if a parent component is passing down the same props as before, the connect wrapper will prevent the wrapped component from re-rendering.
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.
(Source: I'm a Redux maintainer and wrote React-Redux v7.)
来源:https://stackoverflow.com/questions/57833717/how-does-the-behavior-of-a-child-component-using-react-redux-change-when-its-p