Skip to content
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

fix(form): 修复 formitem 的值如果是对象会自动重置为空对象的问题 #2952

Merged
merged 6 commits into from
Jan 22, 2025

Conversation

oasis-cloud
Copy link
Collaborator

@oasis-cloud oasis-cloud commented Jan 20, 2025

🤔 这个变动的性质是?

  • 日常 bug 修复

🔗 相关 Issue

#2870

💡 需求背景和解决方案

merge 方法存在 bug

☑️ 请求合并前的自查清单

⚠️ 请自检并全部勾选全部选项⚠️

  • 文档已补充或无须补充
  • 代码演示已提供或无须提供
  • TypeScript 定义已补充或无须补充
  • fork仓库代码是否为最新避免文件冲突
  • Files changed 没有 package.json lock 等无关文件

Summary by CodeRabbit

  • 新功能

    • 增强了对象合并和克隆的实用函数
    • 提供更灵活的数据合并选项
  • 改进

    • 优化了 mergerecursive 函数的实现
    • 新增了深度克隆和对象类型检测功能
  • Bug 修复

    • 改进了对象合并的安全性
    • 防止原型污染风险
  • 测试

    • 添加了全面的单元测试,覆盖合并、克隆和类型检测函数的各种场景

Copy link

coderabbitai bot commented Jan 20, 2025

演练

此次更改主要涉及 src/utils/merge.ts 文件中合并函数的重构。新的实现引入了更灵活的合并策略,包括克隆和递归合并选项。新增了 cloneisPlainObject 等实用函数,并修改了 mergerecursive 函数的行为。这些变更旨在提高对象合并的功能和代码可读性。

变更

文件 变更摘要
src/utils/merge.ts - 重新设计 merge 函数,新增 main 函数作为默认导出
- 新增 cloneisPlainObject 实用函数
- 添加递归合并支持
src/packages/form/useform.taro.ts - 引入 recursive 函数
- 修改 setFieldsValue 方法的合并逻辑
src/packages/form/useform.ts - 引入 recursive 函数
- 修改 setFieldsValue 方法的合并逻辑
src/packages/form/__tests__/merge.spec.ts - 为新的合并函数添加全面的单元测试

可能相关的 PR

建议的审阅者

  • xiaoyatong

诗歌

兔子轻跳代码海,
合并函数展新颜,
克隆递归皆随意,
对象融合不再难,
代码如诗,兔子欢!🐰✨


📜 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 e2ec3ae and ad40901.

📒 Files selected for processing (1)
  • src/packages/form/useform.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/packages/form/useform.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.

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. (Beta)
  • @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.

Copy link

codecov bot commented Jan 20, 2025

Codecov Report

Attention: Patch coverage is 94.91525% with 3 lines in your changes missing coverage. Please review.

Project coverage is 84.19%. Comparing base (16fb6e5) to head (ad40901).
Report is 2 commits behind head on next.

Files with missing lines Patch % Lines
src/utils/merge.ts 94.73% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             next    #2952      +/-   ##
==========================================
+ Coverage   84.03%   84.19%   +0.15%     
==========================================
  Files         220      267      +47     
  Lines       17917    18099     +182     
  Branches     2628     2661      +33     
==========================================
+ Hits        15057    15238     +181     
- Misses       2855     2856       +1     
  Partials        5        5              

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

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: 2

🧹 Nitpick comments (2)
src/utils/merge.ts (2)

45-51: 优化 isPlainObject 函数的实现方式

当前的实现方法可能影响性能,且代码较为复杂。可以使用更简洁的方法来检查是否为纯对象。

建议使用如下实现:

export function isPlainObject(input: unknown): input is Record<string, any> {
-  if (input === null || typeof input !== 'object') return false
-  if (Object.getPrototypeOf(input) === null) return true
-  let ref = input
-  while (Object.getPrototypeOf(ref) !== null) ref = Object.getPrototypeOf(ref)
-  return Object.getPrototypeOf(input) === ref
+  return Object.prototype.toString.call(input) === '[object Object]'
}

38-38: 在使用 for...in 循环时应考虑属性的可枚举性

直接使用 for...in 可能会遍历到对象原型链上的可枚举属性,建议在循环中加上 hasOwnProperty 检查,确保只遍历对象自身的属性。

修改如下:

- for (const index in input) output[index] = clone((input as any)[index])
+ for (const index in input) {
+   if (Object.prototype.hasOwnProperty.call(input, index)) {
+     output[index] = clone((input as any)[index])
+   }
+ }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 16fb6e5 and 31fab59.

📒 Files selected for processing (1)
  • src/utils/merge.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/utils/merge.ts

[error] 71-71: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (1)
src/utils/merge.ts (1)

60-62: 递归合并时需要考虑数组和非纯对象的处理

在递归合并过程中,目前仅对纯对象进行了处理,可能会忽略数组类型或其他可合并的结构。建议在递归函数中增加对数组类型的支持,或明确处理方式。

请确认在递归合并时,是否需要处理数组类型,避免潜在的问题。

src/utils/merge.ts Show resolved Hide resolved
src/utils/merge.ts Show resolved Hide resolved
@xiaoyatong xiaoyatong changed the title fix(form): formitem 的值如果是对象会自动重置为空对象 fix(form): 修复 formitem 的值如果是对象会自动重置为空对象的问题 Jan 22, 2025
@xiaoyatong xiaoyatong removed the 3.x label Jan 22, 2025
@xiaoyatong
Copy link
Collaborator

@xiaoyatong
Copy link
Collaborator

image

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: 2

🧹 Nitpick comments (1)
src/packages/form/__tests__/merge.spec.ts (1)

147-165: 完善测试用例描述

建议为递归合并的测试用例添加更具体的描述,以便更好地理解每个测试的目的。

-  it('merges recursively', () => {
+  it('should merge nested objects without mutating unrelated properties', () => {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6c91563 and e2ec3ae.

📒 Files selected for processing (3)
  • src/packages/form/__tests__/merge.spec.ts (1 hunks)
  • src/packages/form/useform.taro.ts (2 hunks)
  • src/packages/form/useform.ts (3 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/packages/form/__tests__/merge.spec.ts

[error] 89-89: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 91-91: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 132-132: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 134-134: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (3)
src/packages/form/useform.taro.ts (1)

3-3: 导入并使用 recursive 函数修复对象值重置问题

使用 recursive 替换 merge 是一个很好的改进,它可以正确处理嵌套对象的合并,防止表单项的对象值被重置为空对象。

Also applies to: 101-101

src/packages/form/useform.ts (1)

3-3: 使用 recursive 函数确保深度合并

使用 recursive(true, ...) 替换 merge 可以确保对象值的正确合并,这与 useform.taro.ts 中的修改保持一致。

Also applies to: 101-101

src/packages/form/__tests__/merge.spec.ts (1)

1-263: 测试覆盖全面

测试用例覆盖了所有关键功能,包括对象合并、克隆、递归合并以及边界情况的处理,这对确保代码质量非常重要。

🧰 Tools
🪛 Biome (1.9.4)

[error] 89-89: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 91-91: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 132-132: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 134-134: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@@ -202,7 +202,9 @@ class FormStore {

resetFields = () => {
this.errors.length = 0
console.log('xxx', this.initialValues)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

移除调试日志

建议移除这些控制台日志,因为它们不应该出现在生产代码中。

  resetFields = () => {
    this.errors.length = 0
-   console.log('xxx', this.initialValues)
    const nextStore = merge({}, this.initialValues)
-   console.log(nextStore)
    this.updateStore(nextStore)
    this.fieldEntities.forEach((entity: FormFieldEntity) => {

Also applies to: 207-207

Comment on lines +89 to +91
if (typeof outputValue === 'number' && isNaN(outputValue)) {
// eslint-disable-next-line no-restricted-globals
expect(isNaN(inputValue), key).toBeTruthy()
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

使用 Number.isNaN 替换不安全的全局 isNaN

为了避免类型强制转换带来的潜在问题,建议使用 Number.isNaN

-      if (typeof outputValue === 'number' && isNaN(outputValue)) {
+      if (typeof outputValue === 'number' && Number.isNaN(outputValue)) {
-        expect(isNaN(inputValue), key).toBeTruthy()
+        expect(Number.isNaN(inputValue), key).toBeTruthy()

// 同样在其他位置也需要修改:
-      if (typeof cloned === 'number' && isNaN(cloned)) {
+      if (typeof cloned === 'number' && Number.isNaN(cloned)) {
-        expect(isNaN(value)).toBeTruthy()
+        expect(Number.isNaN(value)).toBeTruthy()

Also applies to: 132-134

🧰 Tools
🪛 Biome (1.9.4)

[error] 89-89: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 91-91: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@xiaoyatong xiaoyatong merged commit 36220ef into jdf2e:next Jan 22, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

nutui-react-taro@2.7.2 FormItem的值如果是对象(如 {label:是,value:1} ),会自动重置成 {}
2 participants