简体   繁体   中英

React.memo and invalidation in Functional component not invalidating

I have a React functional component wrapped with React.memo as follows

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.

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.

Is there a way to not have to pass in this redundant property to get React.memo to recalculate?

This feels like a deep/shallow copy problem but I'm not sure.

memo HOC

The memo HOC simply does a shallow reference equality check of the passed 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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