【问题标题】:How to use React's built-in React.memo comparison function?如何使用 React 内置的 React.memo 比较功能?
【发布时间】:2020-11-02 05:43:54
【问题描述】:

我想检查某个 prop 是否手动更改,然后使用 React 内置的比较功能对其他 prop 进行比较。例如:

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

我可以轻松编写自己的比较函数或从 React 的源代码复制/粘贴,但如果 R​​eact 更改了它们的默认比较函数,那么我也必须手动更改我的函数。有没有办法为React.memo 使用 React 的内置比较功能?

另外,AFAIK,react-addons-shallow-compare 已经过时了。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    很遗憾,没有。如果你不提供比较函数,React 默认为shallowEqual,但如果你返回任何特殊的东西(例如return null),则没有使用默认行为的额外逻辑。

    React's usage:

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

    React 当前没有导出 shallowEqual。但是,React's documentation 声明它只是浅比较,这不太可能发生太大变化,并且可以轻松实现,如您所知 (example)。我假设这个决定是为了减少他们的团队向开发人员公开的 API。

    【讨论】:

    • 供参考,React 的shallowCompare is here;您需要复制他们的Object.isObject.prototype.hasOwnProperty。如果这更容易,我已经制作了a gist,剥离流类型(并根据我自己的喜好稍微重新格式化)。
    • This GH issue(已关闭)请求导出 shallowCompare,但几乎没有讨论就关闭了。如果您觉得这很有用,请在此处添加您的想法。
    猜你喜欢
    • 2012-03-27
    • 2013-02-26
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 2022-07-31
    • 2017-06-07
    • 2016-07-03
    • 1970-01-01
    相关资源
    最近更新 更多