我正在尝试使用react-useMemo来防止组件重新呈现。但不幸的是,它似乎无法解决任何问题,我开始怀疑自己是否做错了
我的组件看起来像这样
function RowVal(props) {
console.log('rendering');
return (
<Row toggleVals={props.toggleVals}>
<StyledTableData centerCell>{props.num}</StyledTableData>
<StyledTableData centerCell borderRight>
{props.percentage}
</StyledTableData>
</Row>
);
}
为了防止重新渲染-我将以下内容添加到了我的父组件中
function ChainRow(props) {
const MemoizedRowVal = useMemo(
() => (
<RowVal
num={props.num}
percentage={props.percentage}
toggleVals={props.toggleVals}
/>
),
[props.toggleVals],
);
return (
<div>{MemoizedRowVal}</div>
)
}
但是尽管布尔值没有变化,但此组件仍保持重新渲染。
我做错什么了吗?
[useMemo
将阻止创建组件的新实例,并且如果道具未更改,也不会阻止其重新渲染
我认为您需要使用React.memo
而不是useMemo
function ChainRow(props) {
return (
<div>
<RowVal
num={props.num}
percentage={props.percentage}
toggleVals={props.toggleVals}
/>
</div>
)
}
const RowVal = React.memo((props) => {
// rowVal code here
});
React.memo
还提供了第二个参数(areEqual),您可以使用它来更好地控制重新渲染
在React中,我们通常将React.Memo用于您的用例。将其包装在子组件上。您可能将它与React.useMemo混淆了。他们是不同的。React.memo
检查该答案。
您可以尝试类似的东西,
Using useMemo instead of React.memo syntax issue