Skip to content

fix(form): fix form setFields rerender #3304

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

Merged
merged 6 commits into from
May 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/components/form/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ const Form = forwardRefWithStatics(
formItemRef?.current.resetField();
});
form?.getInternalHooks?.(HOOK_MARK)?.notifyWatch?.([]);
form.store = {};
onReset?.({ e });
}

Expand Down
37 changes: 29 additions & 8 deletions packages/components/form/FormItem.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { forwardRef, ReactNode, useState, useImperativeHandle, useEffect, useRef, useMemo } from 'react';
import { isObject, isString, get, merge, isFunction } from 'lodash-es';
import { isObject, isString, get, merge, isFunction, set, isEqual } from 'lodash-es';
import {
CheckCircleFilledIcon as TdCheckCircleFilledIcon,
CloseCircleFilledIcon as TdCloseCircleFilledIcon,
Expand Down Expand Up @@ -105,12 +105,17 @@ const FormItem = forwardRef<FormItemInstance, FormItemProps>((originalProps, ref
const [verifyStatus, setVerifyStatus] = useState('validating');
const [resetValidating, setResetValidating] = useState(false);
const [needResetField, setNeedResetField] = useState(false);
const [formValue, setFormValue] = useState(() =>
getDefaultInitialData({
children,
initialData,
}),
);
const [formValue, setFormValue] = useState(() => {
const fieldName = [].concat(formListName, name).filter((item) => item !== undefined);

return (
get(form.store, fieldName) ??
getDefaultInitialData({
children,
initialData,
})
);
});

const formItemRef = useRef<FormItemInstance>(null); // 当前 formItem 实例
const innerFormItemsRef = useRef([]);
Expand Down Expand Up @@ -161,7 +166,23 @@ const FormItem = forwardRef<FormItemInstance, FormItemProps>((originalProps, ref
isUpdatedRef.current = true;
shouldValidate.current = validate;
valueRef.current = newVal;
setFormValue(newVal);

if (formListName) {
const fieldName = [].concat(formListName, name).filter((item) => item !== undefined);

if (!fieldName) return;
const fieldValue = get(form.store, fieldName);
if (isEqual(fieldValue, newVal)) return;
set(form.store, fieldName, newVal);
setFormValue(newVal);
} else {
const fieldName = [].concat(name).filter((item) => item !== undefined);

if (!fieldName) return;
if (isEqual(formValue, newVal)) return;
set(form.store, name, newVal);
setFormValue(newVal);
}
};

// 初始化 rules,最终以 formItem 上优先级最高
Expand Down
44 changes: 43 additions & 1 deletion packages/components/form/__tests__/form-list.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { render, fireEvent, mockTimeout } from '@test/utils';
import { render, fireEvent, mockTimeout, vi } from '@test/utils';
import React from 'react';

import { MinusCircleIcon } from 'tdesign-icons-react';
Expand Down Expand Up @@ -130,4 +130,46 @@ describe('Form List 组件测试', () => {
fireEvent.click(queryByText('clearValidate'));
expect(queryByText('地区必填')).not.toBeTruthy();
});

test('FormList setFields not trigger onValueChange', async () => {
const fn = vi.fn();

const TestView = () => {
const [form] = Form.useForm();

function setFields() {
form.setFields([{ name: 'address', value: [{ province: 'setFields' }] }]);
}

return (
<Form form={form} onValuesChange={fn}>
<FormList name="address">
{(fields) => (
<>
{fields.map(({ key, name, ...restField }) => (
<FormItem key={key}>
<FormItem {...restField} name={[name, 'province']} label="省份">
<Input />
</FormItem>
</FormItem>
))}
</>
)}
</FormList>
<FormItem>
<Button onClick={setFields}>setFields</Button>
</FormItem>
</Form>
);
};

const { queryByText } = render(<TestView />);

fireEvent.click(queryByText('setFields'));
await mockTimeout();
expect(fn).toHaveBeenCalledTimes(1);
fireEvent.click(queryByText('setFields'));
await mockTimeout();
expect(fn).toHaveBeenCalledTimes(1);
});
});
42 changes: 39 additions & 3 deletions packages/components/form/__tests__/form.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import Button from '../../button';
import Radio from '../../radio';
import { HelpCircleIcon } from 'tdesign-icons-react';
import InputNumber from '../../input-number';
import { Checkbox } from 'tdesign-react';

const { FormItem, FormList } = Form;

Expand Down Expand Up @@ -93,13 +94,13 @@ describe('Form 组件测试', () => {
const { getByPlaceholderText, getByText, queryByText } = render(<TestForm />);

// setFields setFieldsValue setValidateMessage test
expect(getByPlaceholderText('input1').value).toEqual('');
expect((getByPlaceholderText('input1') as HTMLInputElement).value).toEqual('');
fireEvent.click(getByText('setFields'));
expect(getByPlaceholderText('input1').value).toEqual('setFields');
expect((getByPlaceholderText('input1') as HTMLInputElement).value).toEqual('setFields');
expect(fn).toHaveBeenCalled();

fireEvent.click(getByText('setFieldsValue'));
expect(getByPlaceholderText('input1').value).toEqual('setFieldsValue');
expect((getByPlaceholderText('input1') as HTMLInputElement).value).toEqual('setFieldsValue');
expect(fn).toHaveBeenCalled();

fireEvent.click(getByText('setValidateMessage'));
Expand Down Expand Up @@ -535,4 +536,39 @@ describe('Form 组件测试', () => {

expect(container.querySelector('.radio-value-3')).toHaveClass('t-is-checked');
});

test('FormItem setFields not trigger onValueChange', async () => {
const fn = vi.fn();

const TestForm = () => {
const [form] = Form.useForm();

function setFields() {
form.setFields?.([{ name: ['user', 'course'], value: ['la'] }]);
}

return (
<Form form={form} labelWidth={100} colon onValuesChange={fn}>
<FormItem label="课程" name={['user', 'course']}>
<Checkbox.Group>
<Checkbox value="la">加辣</Checkbox>
<Checkbox value="ma">加麻</Checkbox>
<Checkbox value="nocong">不要葱花</Checkbox>
</Checkbox.Group>
</FormItem>
<FormItem>
<Button onClick={setFields}>setFields</Button>
</FormItem>
</Form>
);
};
const { getByText, container } = render(<TestForm />);

expect(container.querySelector('.t-is-checked')).toBe(null);
fireEvent.click(getByText('setFields'));
expect((container.querySelector('.t-is-checked input') as HTMLInputElement).value).toEqual('la');
expect(fn).toHaveBeenCalledTimes(1);
fireEvent.click(getByText('setFields'));
expect(fn).toHaveBeenCalledTimes(1);
});
});
2 changes: 1 addition & 1 deletion packages/components/form/hooks/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ export interface InternalHooks {

export interface InternalFormInstance extends FormInstanceFunctions {
_init?: boolean;

store?: Store;
getInternalHooks?: (secret: string) => InternalHooks | null;
}
2 changes: 1 addition & 1 deletion packages/components/form/hooks/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class FormStore {
getFieldValue: null,
getFieldsValue: null,
_init: true,

store: this.store,
getInternalHooks: this.getInternalHooks,
});

Expand Down
4 changes: 2 additions & 2 deletions packages/components/list/List.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { MouseEvent, useImperativeHandle, useMemo, useRef, WheelEvent } from 'react';
import classNames from 'classnames';
import { isString } from 'lodash-es';
import { compact, isString } from 'lodash-es';
import useConfig from '../hooks/useConfig';
import { useLocaleReceiver } from '../locale/LocalReceiver';
import forwardRefWithStatics from '../_util/forwardRefWithStatics';
Expand Down Expand Up @@ -52,7 +52,7 @@ const List = forwardRefWithStatics(
const [local, t] = useLocaleReceiver('list');

const listItems = useMemo(
() => React.Children.map(children, (child: React.ReactElement) => child.props) ?? [],
() => compact(React.Children.map(children, (child: React.ReactElement) => child?.props)) ?? [],
[children],
);

Expand Down