简体   繁体   English

功能组件中的 React.memo 和失效不会失效

[英]React.memo and invalidation in Functional component not invalidating

I have a React functional component wrapped with React.memo as follows我有一个用 React.memo 包装的 React 功能组件,如下所示

const SpeakerDetail = React.memo(
  ({ record, prop1 }) => {...

When I call this component, I do it like this当我调用这个组件时,我会这样做

const record = {prop1: 'abcd', prop2: 'efgh', prop3: 'ijkl'};
const Speakers = () => {
   ...
   return(
      <SpeakerDetail record={record} prop1={record.prop1}></SpeakerDetail>
   )...

Assuming that my prop1 does indeed change between renders, the above code works as expected meaning that React.memo creates a fresh copy and does not use it's cached version.假设我的 prop1 在渲染之间确实发生了变化,上面的代码按预期工作,这意味着 React.memo 创建了一个新副本并且不使用它的缓存版本。

The issue is if I don't explicitly pass prop1 as a separate parameter, the React.memo cache version does not recognize that a property of record has changed.问题是如果我没有明确地将 prop1 作为单独的参数传递,React.memo 缓存版本不会识别记录的属性已更改。

Is there a way to not have to pass in this redundant property to get React.memo to recalculate?有没有办法不必传入这个冗余属性来让 React.memo 重新计算?

This feels like a deep/shallow copy problem but I'm not sure.这感觉像是一个深/浅的复制问题,但我不确定。

memo HOC备忘录 HOC

The memo HOC simply does a shallow reference equality check of the passed props. memo HOC 只是对传递的 props 进行浅层引用相等性检查。 You can specify an equality function as the second parameter to the memo HOC, that takes the previous and next props that returns true if the comparison would return the same result, false otherwise.您可以指定相等 function 作为memo HOC 的第二个参数,如果比较将返回相同的结果,则返回true的上一个和下一个属性,否则返回 false。

const SpeakerDetail = React.memo(
  ({ record, prop1 }) => {...},
  (prevProps, nextProps) => {
    if (prevProps.record.prop1 !== nextProps.record.prop1) return false;
    return true;
  },
);

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

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