Skip to content

优化popup组件 #538

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed

Conversation

765477020
Copy link

@765477020 765477020 commented May 7, 2025

在!forceRender && !open直接return null

Summary by CodeRabbit

  • 性能优化
    • 优化了弹窗内容的渲染逻辑,关闭弹窗或未强制渲染时将不再渲染相关内容,从而提升页面性能。

Copy link

coderabbitai bot commented May 7, 2025

Walkthrough

本次更改调整了弹窗组件的渲染逻辑。只有在弹窗处于打开状态时,才会渲染其子节点。新增了一个提前返回条件:当 forceRender 为 false 且弹窗未打开时,组件直接返回 null,不再渲染任何内容。其余控制流和样式逻辑未做更改。

Changes

文件/文件组 变更摘要
src/Popup/index.tsx 优化弹窗内容的渲染逻辑,仅在弹窗打开时渲染子节点,并增加提前返回条件。

Poem

小兔弹窗轻轻关,
打开才见内容现。
逻辑优化省资源,
代码整洁又新鲜。
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/Popup/index.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-react".

(The package "eslint-plugin-react" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-react@latest --save-dev

The plugin "eslint-plugin-react" was referenced from the config file in ".eslintrc.js » /node_modules/.pnpm/@umijs+fabric@4.0.1_postcss@8.5.3/node_modules/@umijs/fabric/dist/eslint.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bb94258 and c485143.

📒 Files selected for processing (1)
  • src/Popup/index.tsx (2 hunks)
🔇 Additional comments (2)
src/Popup/index.tsx (2)

124-125: 优化了条件渲染逻辑

这个修改调整了 childNode 的赋值逻辑,只有在弹窗打开时才会渲染其子节点。这种逻辑更加合理,可以减少不必要的渲染计算,尤其是当 popup 是一个函数时,避免了在弹窗关闭时执行该函数。


203-205: 提前返回优化非常有效

这个提前返回条件很好地优化了性能。当 forceRender 为 false 且弹窗未打开时,组件直接返回 null,避免了不必要的渲染流程。这与 Portal 组件的 open={forceRender || isNodeVisible} 条件保持一致,但通过提前返回进一步优化了性能,减少了不必要的组件实例化和计算。

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@@ -199,6 +200,10 @@ const Popup = React.forwardRef<HTMLDivElement, PopupProps>((props, ref) => {
miscStyle.pointerEvents = 'none';
}

if (!forceRender && !open) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这些逻辑可能没有必要,Portal 里已经对 forceRender 做了处理。如果是非 open 且没有 forceRender 是不会渲染的

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

我用修改前和修改后代码,跑了一下一次性创建2w个trigger,上面是用时对比,分别做了三次对比

看到Portal里面也有React.cloneElement这个操作

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

所以损耗比较多的是来自 cloneElement 的代码是吧?感谢调试,我想想怎么链路上去优化一下,Portal 本身应该是让人无脑用的,如果上游还要优化就不是封装 Portal 的目的了

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

我拉了一下火焰图(禁用 React Dev Tools),cloneElement 是少于 createElement 的:

截屏2025-05-14 15 47 56

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

从 createElement 上看,rc-trigger 的 TriggerWrapper 可以省略,但是需要把所有依赖动态 ref 的组件的 getTriggerDOMNode 给收掉。我看看是否可以实现

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

另外还有一点,React 的 dev 和 prod 的对 ReactElement 性能损耗是不一样的。createElement 的慢在于 dev 下会做额外的注入:

    function ReactElement(
      type,
      key,
      self,
      source,
      owner,
      props,
      debugStack,
      debugTask
    ) {
      self = props.ref;
      type = {
        $$typeof: REACT_ELEMENT_TYPE,
        type: type,
        key: key,
        props: props,
        _owner: owner
      };
      null !== (void 0 !== self ? self : null)
        ? Object.defineProperty(type, "ref", {
            enumerable: !1,
            get: elementRefGetterWithDeprecationWarning
          })
        : Object.defineProperty(type, "ref", { enumerable: !1, value: null });
      type._store = {};
      Object.defineProperty(type._store, "validated", {
        configurable: !1,
        enumerable: !1,
        writable: !0,
        value: 0
      });
      Object.defineProperty(type, "_debugInfo", {
        configurable: !1,
        enumerable: !1,
        writable: !0,
        value: null
      });
      Object.defineProperty(type, "_debugStack", {
        configurable: !1,
        enumerable: !1,
        writable: !0,
        value: debugStack
      });
      Object.defineProperty(type, "_debugTask", {
        configurable: !1,
        enumerable: !1,
        writable: !0,
        value: debugTask
      });
      Object.freeze && (Object.freeze(type.props), Object.freeze(type));
      return type;
    }

而 prod 则不会:

function ReactElement(type, key, self, source, owner, props) {
  self = props.ref;
  return {
    $$typeof: REACT_ELEMENT_TYPE,
    type: type,
    key: key,
    ref: void 0 !== self ? self : null,
    props: props
  };
}

所以对于 createElement or cloneElement 的优化主要是提升了 dev 下的体验。

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

其实 createElement是必要操作,也不需要关心他们两个谁的效率更高
我的观点是,代码中尽可能的少用不用cloneElement代码,正如你说的TriggerWrapper中的cloneElement可以和外面的cloneElement操作合并成一次

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

假设完成许许多多的性能优化,lim性能趋向于正无穷=<></>
在大批量的渲染面前,渲染100万个<></>和渲染100万个null肯定也是前者耗时长
所以const childNode =(open && (typeof popup === 'function' ? popup() : popup)) || null;这行代码的存在是非常有必要的

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

嗯,v6 里不需要 findDOMNode,先干掉一个 #539

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#540 我调了一下,在更外层来处理把 Popup 和 ContextProvider 也省一下,帮我 CR 一下

@765477020 765477020 closed this May 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants