react-component / react-component/field-form
useWatch支持dynamic path
Nobody has claimed this yet.
- Dominant language
- TypeScript
- Stars
- 1k
- Forks
- 286
- Avg merge
- 4d 16h
- Merged PRs (30d)
- 1
Description
为什么不支持watch动态的路径呢?事实上我传一个动态的namePath,它似乎也能正常工作,只是代码里写了让它warnning。但如果我传了一个动态的selector,它不起效,selector会保持不变,我想是否因为这里effect没有依赖dependencies(when type is func)。所以为什么不加上这个依赖呢?然后不用ref来接受namePath,将namePath也放入依赖中,似乎这样就支持动态路径,而不必报错了。
// in useWatch
useEffect(
() => {
// Skip if not exist form instance
if (!isValidForm) {
return;
}
const { getFieldsValue, getInternalHooks } = formInstance;
const { registerWatch } = getInternalHooks(HOOK_MARK);
const getWatchValue = (values: any, allValues: any) => {
const watchValue = options.preserve ? allValues : values;
return typeof dependencies === 'function'
? dependencies(watchValue)
: getValue(watchValue, namePathRef.current);
};
const cancelRegister = registerWatch((values, allValues) => {
const newValue = getWatchValue(values, allValues);
const nextValueStr = stringify(newValue);
// Compare stringify in case it's nest object
if (valueStrRef.current !== nextValueStr) {
valueStrRef.current = nextValueStr;
setValue(newValue);
}
});
// TODO: We can improve this perf in future
const initialValue = getWatchValue(getFieldsValue(), getFieldsValue(true));
// React 18 has the bug that will queue update twice even the value is not changed
// ref: https://github.com/facebook/react/issues/27213
if (value !== initialValue) {
setValue(initialValue);
}
return cancelRegister;
},
// We do not need re-register since namePath content is the same
// eslint-disable-next-line react-hooks/exhaustive-deps
[isValidForm],
);
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at the useWatch implementation and inspect the effect shown in the issue, focusing on dynamic selector and namePath handling. Reproduce both cases and trace how dependencies and refs affect updates. Done means dynamic selectors and paths update correctly without the current warning or stale selector behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- react, typescript
- Domain
- frontend
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100