为什么 React.memo 和 shouldComponentUpdate 不做同样的事情?
Why React.memo and shouldComponentUpdate aren't doing the same?
我有一个功能组件,它与我的 Redux 存储中的一个对象有连接。为了避免在对象更改时重新渲染,我添加了 React.memo
,但是,这并没有避免重新渲染。我的备忘录看起来像这样:
const MemoizedRadio = React.memo(Radio, (prevProps, nextProps) => {
if (prevProps.selected !== nextProps.selected) {
return false;
}
return true;
});
const mapStateToProps = state => ({
nodes: state.canvas.elements.nodes
});
export default connect(mapStateToProps)(MemoizedRadio);
如果 nodes
对象已更改,我希望此组件不会重新呈现,但确实如此。
当我将组件重写为 class 组件并添加 shouldComponentUpdate 时,将按预期阻止重新渲染。 shouldComponentUpdate 如下所示:
shouldComponentUpdate(nextProps) {
if (this.props.selected !== nextProps.selected) {
return true;
}
return false;
}
我认为 React.memo
与 shouldComponentUpdate
的行为相同,但事实并非如此。当对 nodes
对象的引用更改时,React.memo
实现总是重新渲染,而 shouldComponentUpdate
实现阻止按预期重新渲染。
任何人都可以解释这种行为吗?
您正在正确使用 React.memo
,问题是您正在使用 connect
HOC 将基于 class 的组件连接到商店。而不是使用 HOC 你应该使用 useDispatch
和 useSelector
我有一个功能组件,它与我的 Redux 存储中的一个对象有连接。为了避免在对象更改时重新渲染,我添加了 React.memo
,但是,这并没有避免重新渲染。我的备忘录看起来像这样:
const MemoizedRadio = React.memo(Radio, (prevProps, nextProps) => {
if (prevProps.selected !== nextProps.selected) {
return false;
}
return true;
});
const mapStateToProps = state => ({
nodes: state.canvas.elements.nodes
});
export default connect(mapStateToProps)(MemoizedRadio);
如果 nodes
对象已更改,我希望此组件不会重新呈现,但确实如此。
当我将组件重写为 class 组件并添加 shouldComponentUpdate 时,将按预期阻止重新渲染。 shouldComponentUpdate 如下所示:
shouldComponentUpdate(nextProps) {
if (this.props.selected !== nextProps.selected) {
return true;
}
return false;
}
我认为 React.memo
与 shouldComponentUpdate
的行为相同,但事实并非如此。当对 nodes
对象的引用更改时,React.memo
实现总是重新渲染,而 shouldComponentUpdate
实现阻止按预期重新渲染。
任何人都可以解释这种行为吗?
您正在正确使用 React.memo
,问题是您正在使用 connect
HOC 将基于 class 的组件连接到商店。而不是使用 HOC 你应该使用 useDispatch
和 useSelector