Skip to content

useWatch支持dynamic path #746

Open
@lilinhao1054

Description

@lilinhao1054

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions