javascript - How to use React's built-in React.memo comparison function? - Stack Overflow

I want to check whether a certain prop changed manually, then use React's built-in parison functio

I want to check whether a certain prop changed manually, then use React's built-in parison function for the other props. E.g.:

React.memo(
  () => <div />,
  (prevProps, nextProps) => {
    if (!nextProps.visible) {
      return true;
    }
    return React.shallowCompare(prevProps, nextProps);
  },
);

I can easily write my own parison function or copy/paste from React's source, but if React changes their default parison function then I'd have to manually change my function too. Is there a way to use React's built-in parison function for React.memo?

Also, AFAIK, react-addons-shallow-pare is outdated.

I want to check whether a certain prop changed manually, then use React's built-in parison function for the other props. E.g.:

React.memo(
  () => <div />,
  (prevProps, nextProps) => {
    if (!nextProps.visible) {
      return true;
    }
    return React.shallowCompare(prevProps, nextProps);
  },
);

I can easily write my own parison function or copy/paste from React's source, but if React changes their default parison function then I'd have to manually change my function too. Is there a way to use React's built-in parison function for React.memo?

Also, AFAIK, react-addons-shallow-pare is outdated.

Share Improve this question asked Jul 13, 2020 at 3:40 Leo JiangLeo Jiang 26.3k59 gold badges177 silver badges328 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

Unfortunately, no. React defaults to shallowEqual in the event you don't provide a pare function, but there isn't additional logic for using the default behavior if you return anything special (e.g. return null).

React's usage:

const prevProps = currentChild.memoizedProps;
// Default to shallow parison
let pare = Component.pare;
pare = pare !== null ? pare : shallowEqual;
if (pare(prevProps, nextProps) && current.ref === workInProgress.ref) {
...

React isn't currently exporting shallowEqual. However, React's documentation states that it only shallow pares, which is unlikely to change much and can be trivially implemented as you know (example). I'm assuming this decision is to reduce the API their team exposes to developers.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745198521a4616209.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信