繁体   English   中英

使用 React.memo() 记忆的组件不断重新渲染

[英]Component memoized with React.memo() keeps re-rendering

我有一个ParentComponent看起来像这样:

const ParentComponent = () => {
  [product, setProduct] = useState({
    name: "Test",
    description: "Information goes here..."
  })

  return(
    <ChildComponent product={product} updateProduct={setProduct}/>
  );
}

ChildComponent如下:

const ChildComponent = ({product, updateProduct}) => {
  // some code here

  return(
    <RichTextEditor content={product.description} update={updateProduct}/>
  )
}

const isEqual = () => {
  return true; // I want to force the component to never re-render
}

export default React.memo(ChildComponent, isEqual)

这里发生的是我有一个product对象,其描述由ChildComponent更新。 每次RichTextEditor组件中的输入更改时,都会通过updateProduct设置描述的值。 我知道由于product的状态更改, ChildComponent每次都会重新渲染,这是不幸的,因为这可能会导致不需要的效果,例如使RichTextEditor中的输入字段失去焦点。 因此,我尝试使用始终返回 true 的isEqual函数强制ChildComponent永远不要重新渲染。 但它一直在重新渲染,这是为什么呢?

我意识到还有其他设计可以完全避免这个问题,无论如何我可能都会这样做,但在我这样做之前,我想了解为什么我不能强制ChildComponent不重新渲染。

如果您使用的是useStateuseContextuseReducer ,那么组件仍将重新渲染。

这直接来自文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM