我应该使用shouldComponentupdate吗?

时间:2019-05-23 02:52:14

标签: reactjs react-hooks

最近,我意识到当父项更改甚至道具和子项状态不变时,子项总是会重新渲染。这使我的项目太慢了。 所以,我用shouldComponentupdate来解决这个问题。 但是,我真的应该使用它吗?

如果我应该使用它。有什么方法可以将其应用于React-hook

这是我的shouldComponentupdate

中的代码
shouldComponentupdate(nextProps, nextState){
if(JSON.stringify(nextProps) !== JSON.stringify(this.props) ||
JSON.stringify(nextState) !== JSON.stringify(this.state)
){
 return true
}
return false
}

非常感谢您!

2 个答案:

答案 0 :(得分:1)

基于您只是将当前道具/状态与以前的道具/状态进行比较的事实,您应该能够删除shouldComponentUpdate并使用PureComponent。唯一的区别是PureComponent会进行浅层道具/状态检查,而您正在使用JSON.stringify进行深层值相等检查,因此您应确保浅层检查仍在进行优化。

class MyComponent extends PureComponent { // No need for shouldComponentUpdate

功能组件(包括使用钩子的组件)的等效功能为React.memo

function MyComponent(props) {
  ...
}

export default React.memo(MyComponent);

答案 1 :(得分:0)

父组件的重新渲染将始终触发其所有子组件的重新渲染。因此,在子组件中实现shouldComponentUpdate将无济于事。

您可以使用的一种解决方案是将父组件的当前道具/状态委托给较低的道具/状态,即,在子组件上侦听道具并渲染UI,并让父组件跟踪较少的物品。

相关问题