Javascript 如何防止我的React组件不必要地渲染?
我有一个react应用程序。在这个应用程序中,我渲染了10个表。当用户对一个表进行更改时,我只希望重新呈现一个表,而不是全部10个表 为了完成这项任务,我使用了带有比较器函数的Javascript 如何防止我的React组件不必要地渲染?,javascript,reactjs,performance,Javascript,Reactjs,Performance,我有一个react应用程序。在这个应用程序中,我渲染了10个表。当用户对一个表进行更改时,我只希望重新呈现一个表,而不是全部10个表 为了完成这项任务,我使用了带有比较器函数的React.usemo()。这是: function areEqual(prevProps, nextProps) { /* return true if passing nextProps to render would return the same result as passing prevProps
React.usemo()
。这是:
function areEqual(prevProps, nextProps) {
/*
return true if passing nextProps to render would return
the same result as passing prevProps to render,
otherwise return false
*/
const { categoryTotal: ctPrev, ...prev } = prevProps;
const { categoryTotal: ctNext, ...next } = nextProps;
if (
!ctPrev.totalPrice.eq(ctNext.totalPrice) &&
!ctPrev.totalWeight.eq(ctNext.totalWeight) &&
!ctPrev.totalWorn.eq(ctNext.totalWorn) &&
!ctPrev.totalConsumable.eq(ctNext.totalConsumable)
) {
console.log('totals did change')
return false;
}
for (var key in next) {
if (next[key] !== prev[key]) {
console.log('not equal', key);
return false;
}
}
console.log('props did not change')
return true;
}
export default React.memo(CategoryTable, areEqual);
我已经验证了除了更改的表之外,每个表都返回true。所以只有一个表应该重新呈现,而不是全部10个,对吗?错。这是我的火焰图:
我的表组件的名称是CategoryTable。如您所见,类别表(备注)显示为灰色,但随后的类别表显示为绿色,并与其所有子项一样进行渲染。我已经通过在CategoryTable组件中放置一个console.log来确认每个category表都在呈现
如何实际阻止此组件重新渲染?react.memo是否会阻止树中下面的所有组件渲染或仅渲染已包装的组件?react.memo返回cach如果值没有更改其实际用途,但在您的情况下,您可以尝试使用pureComponent,如果子组件的道具没有更改,它将阻止渲染子组件pureComponent执行与memo相同的操作。唯一的区别是PureComponent用于类组件,memo if用于功能组件。您可以尝试在
shouldComponentUpdate
生命周期函数中使用areEqual
函数。如果没有任何更改,只需返回false。