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 change not trigger useWatch of formlist #2904

Merged
merged 2 commits into from
May 16, 2024
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
2 changes: 1 addition & 1 deletion src/form/FormItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ const FormItem = forwardRef<FormItemInstance, FormItemProps>((originalProps, ref

filterRules.length && validate('change');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [formValue]);
}, [formValue, name]);

// 暴露 ref 实例方法
const instance: FormItemInstance = {
Expand Down
10 changes: 5 additions & 5 deletions src/form/hooks/useWatch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState, useEffect, useMemo, useRef } from 'react';
import get from 'lodash/get';
import isUndefined from 'lodash/isUndefined';
import type { NamePath } from '../type';
import type { InternalFormInstance } from './interface';
import { HOOK_MARK } from './useForm';
Expand All @@ -18,26 +19,25 @@ export default function useWatch(name: NamePath, form: InternalFormInstance) {

const { registerWatch = noop } = form.getInternalHooks?.(HOOK_MARK);

const cancelRegister = registerWatch((_values, paths) => {
if (String(name) !== String(paths)) return;
const cancelRegister = registerWatch(() => {
const allFieldsValue = form.getFieldsValue?.(true);
const newValue = get(allFieldsValue, name);
const nextValueStr = JSON.stringify(newValue);

// Compare stringify in case it's nest object
if (valueStrRef.current !== nextValueStr) {
valueStrRef.current = nextValueStr;
setValue(newValue);
setValue(nextValueStr);
}
});

const allFieldsValue = form.getFieldsValue?.(true);
const initialValue = get(allFieldsValue, name);
setValue(initialValue);
setValue(JSON.stringify(initialValue));

return cancelRegister;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return value;
return isUndefined(value) ? value : JSON.parse(value);
}
Loading