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

useWatch支持dynamic path #746

Open
lilinhao1054 opened this issue Jan 4, 2025 · 0 comments
Open

useWatch支持dynamic path #746

lilinhao1054 opened this issue Jan 4, 2025 · 0 comments

Comments

@lilinhao1054
Copy link

为什么不支持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],
  );
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

No branches or pull requests

1 participant