Skip to content

Conversation

@QDyanbing
Copy link
Contributor

@QDyanbing QDyanbing commented Dec 16, 2025

fix: ant-design/ant-design#56242

Summary by CodeRabbit

发布说明

  • Bug修复
    • 改进了表单列表根字段值的处理:当表单存储已有值时会保留该值,仅在既无合并值也无存储值时才默认为空,避免在渲染时意外重置列表数据。
  • 测试
    • 新增单元测试覆盖列表根字段场景,验证在嵌套字段未由父字段包裹时能正确返回列表根的值。

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link

vercel bot commented Dec 16, 2025

@QDyanbing is attempting to deploy a commit to the React Component Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link

coderabbitai bot commented Dec 16, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

修改 getFieldsValue 中对 Form.List 根路径的合并逻辑:当 mergedValues 没有该路径时,优先读取 store 中对应值;仅当两者都为 undefined 时才回退为空数组([]),避免在渲染时无条件覆盖已有列表值。

Changes

Cohort / File(s) 更改摘要
Form.List 值提取逻辑修复
src/useForm.ts
调整 getFieldsValue:对 Form.List 根路径不再无条件写入 [],改为优先使用 mergedValues 的值,若为 undefined 则回退到 store 中的值,只有两者均无值时才置为 []
新增测试覆盖边界场景
tests/list.test.tsx
添加测试 "getFieldsValue should return list root value when Form.List is not wrapped by parent Field",验证在 List 内字段未被父 Field 包裹时,getFieldsValue(['list']) 返回根列表的实际值(包含对象项)。

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 分钟

  • 关注 src/useForm.tsgetFieldsValue 的分支逻辑、路径解析与边界条件处理(mergedValues vs store 值判断)。
  • 检查新增测试 tests/list.test.tsx 是否完整覆盖场景(未包裹 Field、已有 store 值、多个行的行为)。
  • 注意引用传递与可变对象(store 返回数组/对象时是否需防御性拷贝)。

Possibly related PRs

Poem

🐰 小兔在表单林,轻踩每一行,
若旧仓藏有值,我便默默寻回;
不再胡乱涂白,只在真无时铺开。 🥕✨

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed PR标题准确地总结了主要变更:修复当Form.List未被包裹时getFieldsValue返回错误值的问题。
Linked Issues check ✅ Passed 代码变更满足#56242的核心需求,修复了getFieldsValue(['list'])与form.getFieldsValue()返回值不一致的问题。
Out of Scope Changes check ✅ Passed 所有变更都专注于修复getFieldsValue中Form.List根值的处理逻辑,以及添加相应的测试用例,无范围外的改动。
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 90336e1 and fce8ad7.

📒 Files selected for processing (1)
  • src/useForm.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/useForm.ts

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.

@gemini-code-assist
Copy link

Summary of Changes

Hello @QDyanbing, 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 addresses a specific bug in the form handling logic of ant-design where getFieldsValue was not accurately retrieving values for Form.List components under certain conditions. By adjusting the value retrieval mechanism to first check the internal store for values when a Form.List is not wrapped by a parent Field, it ensures that the form's state is consistently and correctly reflected, improving data integrity and preventing unexpected data loss or incorrect empty array returns.

Highlights

  • Form.List Value Retrieval Fix: Corrects an issue where getFieldsValue might return an empty array for Form.List components that are not explicitly wrapped by a parent Field component.
  • Improved Value Consistency: Ensures that the actual stored value for such Form.List components is retrieved from the form's internal store if available, preventing incorrect defaulting to an empty array.
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 by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

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 pull request 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

This pull request addresses an issue where getFieldsValue would incorrectly return an empty array for a Form.List when its name was passed directly, instead of its actual value from the store. The new logic correctly retrieves the value from the main store, and only defaults to an empty array if the value is not found. This is a solid fix that improves the component's behavior. I have one minor suggestion to enhance code conciseness.

src/useForm.ts Outdated
mergedValues = setValue(
mergedValues,
namePath,
storeListValue === undefined ? [] : storeListValue,

Choose a reason for hiding this comment

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

medium

For improved readability and conciseness, you can use the nullish coalescing operator (??) to provide a default value for storeListValue when it is null or undefined.

Suggested change
storeListValue === undefined ? [] : storeListValue,
storeListValue ?? [],

Copy link
Contributor Author

Choose a reason for hiding this comment

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

?? 会漏null

Copy link
Member

Choose a reason for hiding this comment

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

是 storeListValue === undefined 会漏 null, ??不会

Copy link
Member

Choose a reason for hiding this comment

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

你目的只想判断undefined的话,就不用理会它

Copy link
Contributor Author

Choose a reason for hiding this comment

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

我的意思就是只想判断undefined;null的时候不处理成[]

@yoyo837
Copy link
Member

yoyo837 commented Dec 16, 2025

请添加一个测试用例覆盖一下

@codecov
Copy link

codecov bot commented Dec 16, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.53%. Comparing base (3247c62) to head (f12ffea).

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #770   +/-   ##
=======================================
  Coverage   99.53%   99.53%           
=======================================
  Files          19       19           
  Lines        1299     1302    +3     
  Branches      319      320    +1     
=======================================
+ Hits         1293     1296    +3     
  Misses          6        6           

☔ 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.

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)
tests/list.test.tsx (1)

1143-1176: 建议增强测试以完全覆盖原始问题场景

当前测试正确验证了 getFieldsValue(['list']) 的返回值。但根据关联的 issue #56242,原始问题是 form.getFieldsValue()form.getFieldsValue(['list']) 返回不同的值,而它们应该返回相等的值。

建议添加断言来验证两种调用方式返回相同的结果,以更全面地覆盖修复场景。

在现有断言后添加以下代码:

     expect(form.current?.getFieldsValue(['list'])).toEqual({
       list: [{ name: 'n1', value: '1' }],
     });
+
+    // Verify both call patterns return the same result (issue #56242)
+    expect(form.current?.getFieldsValue()).toEqual(
+      form.current?.getFieldsValue(['list'])
+    );
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f12ffea and 90336e1.

📒 Files selected for processing (1)
  • tests/list.test.tsx (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
tests/list.test.tsx (3)
src/List.tsx (1)
  • ListOperations (23-27)
tests/common/InfoField.tsx (1)
  • Input (9-11)
tests/common/index.ts (2)
  • changeValue (27-39)
  • getInput (5-25)

@ShenHongFei
Copy link

@QDyanbing 你的这个 pr 我已经通过 patch node_modules 应用了,这个 getFieldsValue 的问题应该是修复了。但是又发现了 Form 的 onValuesChange 回调中,收到的 allValues 参数也不对的问题,对应字段也是 Form.List,调试了下发现 mergedAllValues 中数组从原来的 6 项变成了仅剩修改的那一项,所有别的字段也丢失了,可以帮忙看看嘛?应该是类似的修改方法?
image
image

@ShenHongFei
Copy link

https://codesandbox.io/p/devbox/jolly-platform-p68tsv

复现了

function Test() {
  interface Fields {
    list: { name: string; value: number }[];
  }

  let [alls, set_alls] = useState<Fields["list"]>([]);

  return (
    <>
      <Form<Fields>
        className=""
        onValuesChange={(changeds, alls) => {
          set_alls(alls.list);
        }}
      >
        {/* 没有这个 Form.Item 的情况下,onValuesChange 的 alls 参数有问题 */}
        {/* <Form.Item<Fields> name='list' label='list'> */}
        <Form.List
          name="list"
          initialValue={[
            { name: "a", value: "1" },
            { name: "b", value: "2" },
          ]}
        >
          {(fields, { add }, { errors }) => (
            <>
              {fields.map(({ name, key }) => (
                <div key={name} className="list-item">
                  <Form.Item name={[name, "name"]} label="name">
                    <Input />
                  </Form.Item>

                  <Form.Item name={[name, "value"]} label="value">
                    <Input />
                  </Form.Item>
                </div>
              ))}
            </>
          )}
        </Form.List>
        {/* </Form.Item> */}
      </Form>

      <div>onValuesChange alls: {JSON.stringify(alls)}</div>
    </>
  );
}

@QDyanbing
Copy link
Contributor Author

好的,我看看

@QDyanbing
Copy link
Contributor Author

看起来应该和本次改动无关,明天我确认下这里的valuemerge逻辑

@QDyanbing QDyanbing closed this Dec 18, 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.

Form.List 未包裹在 Form.Item 内时 form.getFieldsValue(['list']) 返回值错误

3 participants