Skip to content

Conversation

@EmilyyyLiu
Copy link
Contributor

@EmilyyyLiu EmilyyyLiu commented Sep 12, 2025

关联issue:ant-design/ant-design#54854
替换 useMergedState 为 useControlledState

Summary by CodeRabbit

  • 新特性
  • 重构
    • 优化开关组件的状态管理,使受控/非受控场景下行为更一致并减少边界问题,对外 API 不变,无需迁移。
  • 杂务
    • 更新依赖至最新小版本,带来兼容性与稳定性改进。

@coderabbitai
Copy link

coderabbitai bot commented Sep 12, 2025

Walkthrough

将依赖 @rc-component/util 从 ^1.2.0 升级到 ^1.3.0;在 Switch 组件中用 useControlledState 替换 useMergedState 管理受控/非受控的 checked 状态,初始化逻辑改为以 defaultChecked ?? false 为初值并接受 checked 作为受控值。未改动任何导出签名。

Changes

Cohort / File(s) 摘要
依赖版本更新
package.json
@rc-component/util 版本从 ^1.2.0 升至 ^1.3.0
Switch 内部状态管理
src/index.tsx
useMergedState 替换为 useControlledState;初始化从 useMergedState(false, { value: checked, defaultValue: defaultChecked }) 改为 useControlledState(defaultChecked ?? false, checked);同步更新对应的 import 路径。无导出/API 变更。

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User as 用户
  participant Switch as Switch 组件
  participant Hook as useControlledState
  participant Parent as 父组件

  User->>Switch: 点击/切换
  Note right of Switch: 从 props 读取<br/>checked / defaultChecked
  Switch->>Hook: 初始化: useControlledState(defaultChecked ?? false, checked)
  Hook-->>Switch: 返回 [value, setValue]
  alt 受控 (checked 提供)
    Switch->>Parent: 触发 onChange(nextChecked)
    Parent-->>Switch: 通过 props.checked 传回受控值
    Switch->>Hook: 同步受控 value
  else 非受控 (无 checked)
    Switch->>Hook: setValue(nextChecked)
    Switch->>Parent: 触发 onChange(nextChecked)
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • zombieJ

Pre-merge checks (2 passed, 1 warning)

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed 标题直接且准确地概括了 PR 的核心变更(升级 utils 依赖并替换 useMergedState 钩子),表述简洁明了,没有多余噪音,便于团队快速识别主要意图。

Poem

小兔叼着版本草,跃过依赖的篱笆梢 🥕
旧钩子轻轻告别,新的受控把手招
开关一拨亮与暗,状态自有佳妙
咔哒一声风循路,默契在代码里欢跳

✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @EmilyyyLiu, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refactors the component's internal state management by updating a core utility library and migrating to a more explicit controlled state hook. This change aligns with the latest version of @rc-component/util, ensuring the component leverages improved state handling mechanisms for better predictability and maintainability, as indicated by the related issue.

Highlights

  • Dependency Upgrade: The @rc-component/util dependency has been upgraded from version ^1.2.0 to ^1.3.0.
  • State Hook Replacement: The useMergedState hook has been replaced with useControlledState in src/index.tsx for managing component state, aligning with the updated utility library.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

本次 PR 升级了 @rc-component/util 依赖,并使用 useControlledState 替换了 useMergedState。这一重构使得状态管理逻辑更清晰,并且与新版工具库的 API 保持一致。useControlledState 的用法 defaultChecked ?? false 正确地处理了非受控情况下的默认值。代码改动正确,没有发现问题。

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/index.tsx (1)

52-55: 状态初始化与受控值顺序正确;可做一次轻量懒初始化微调

当前写法等价于原逻辑,建议用懒初始化避免每次渲染都计算默认值(虽为布尔,微优化即可):

-    const [innerChecked, setInnerChecked] = useControlledState<boolean>(
-      defaultChecked ?? false,
-      checked,
-    );
+    const [innerChecked, setInnerChecked] = useControlledState<boolean>(
+      () => (defaultChecked ?? false),
+      checked,
+    );

另,受控切换为非受控(checked 从 boolean → undefined)时,请确认不会短暂出现 innerChecked === undefined 影响 aria-checked 与样式判定;若需兜底,可在渲染处对布尔值取整(可选优化)。

可用以下片段在本组件层面补一条行为测试(思路):

// 伪代码:从受控(true)切到非受控(undefined)后,aria-checked 应仍为 'true' 或回落为 'false' 而非缺失
// render(<Switch checked defaultChecked={false} />)
// rerender(<Switch defaultChecked={false} />) // checked -> undefined
// expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', expect.stringMatching(/^(true|false)$/))
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 86b7162 and 5787f0b.

📒 Files selected for processing (2)
  • package.json (1 hunks)
  • src/index.tsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Socket Security: Pull Request Alerts
🔇 Additional comments (2)
package.json (1)

47-47: 已移除 useMergedState;需验证构建能解析新导入路径

检查结果:未在 src/** 中发现 useMergedState;src/index.tsx 从 '@rc-component/util/lib/hooks/useControlledState' 和 '@rc-component/util/lib/KeyCode' 导入。
动作:在本地或 CI 运行完整构建/打包以验证上述路径在构建产物中可解析;若解析失败,改为使用包的公共导出或调整导入路径(位置:src/index.tsx)。

src/index.tsx (1)

3-3: 切换到 useControlledState 的引入路径正确

@rc-component/util@1.3.0 已新增该 Hook,lib/hooks/useControlledState 可用。与该版本的变更相符。 (github.com)

@codecov
Copy link

codecov bot commented Sep 16, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (86b7162) to head (5787f0b).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master      #161   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            1         1           
  Lines           34        34           
  Branches         8         9    +1     
=========================================
  Hits            34        34           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@zombieJ zombieJ merged commit c127aad into react-component:master Sep 16, 2025
7 checks passed
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