React useMemo重新渲染问题

问题描述 投票:0回答:2

我正在尝试使用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>
  );
}
  • toggleVals是一个布尔值
  • num是整数
  • 百分比prop是浮点值

为了防止重新渲染-我将以下内容添加到了我的父组件中

function ChainRow(props) {
 const MemoizedRowVal = useMemo(
    () => (
      <RowVal
        num={props.num}
        percentage={props.percentage}
        toggleVals={props.toggleVals}
      />
    ),
    [props.toggleVals],
  );

  return (

   <div>{MemoizedRowVal}</div>
  )

}

但是尽管布尔值没有变化,但此组件仍保持重新渲染。

我做错什么了吗?

reactjs
2个回答
0
投票

[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),您可以使用它来更好地控制重新渲染


0
投票

在React中,我们通常将React.Memo用于您的用例。将其包装在子组件上。您可能将它与React.useMemo混淆了。他们是不同的。React.memo检查该答案。

您可以尝试类似的东西,

Using useMemo instead of React.memo syntax issue
© www.soinside.com 2019 - 2024. All rights reserved.