useFormWatch
为啥要写这个hooks?主要是因为我们页面antd使用的是4.0版本,当时5.0还没有支持,而在一些业务场景中我需要监听某个表单值的变化来做一些回调处理,而Form
组件的props
中onValuesChange
需要集中一个地方来写这些回调又不太方便于是便翻到了源码中RC_FORM_INTERNAL_HOOKS
这个antd内置hooks事件,可以用来监听
import {
FormInstance } from 'antd';
import {
useEffect, useRef } from 'react';
export default function useFormWatch(
fn: (v: {
[x: string]: any }) => void,
form?: FormInstance<any>,
keyDeps: string[],
) {
const preValue = useRef({
});
const preValueKey = Object.keys(preValue.current);
// 删除不需要监控key
preValueKey.forEach((key) => {
if (!keyDeps.includes(key)) {
delete preValue.current[key];
}
});
// 新增监控key
keyDeps.forEach((key) => {
if (typeof key != 'string') {
throw new Error('keyDeps must be string');
}
if (!preValueKey.includes(key)) {
preValue.current[key] = undefined;
}
});
useEffect(() => {
if (!form) {
return;
}
const formValue = form.getFieldsValue();
Object.keys(preValue.current).forEach((key) => {
preValue.current[key] = formValue[key];
});
}, [Object.keys(preValue.current).join(), form]);
useEffect(() => {
if (!form) {
return;
}
/**
* 表单初始化是异步的,在组件挂载时对应值可能还没有赋值
* https://github1s.com/react-component/field-form/blob/HEAD/src/useForm.ts#L99-L100
*/
//@ts-ignore
const destroyWatch = form
?.getInternalHooks('RC_FORM_INTERNAL_HOOKS')
?.registerWatch((value: any) => {
const obj = {
};
keyDeps.forEach((key) => {
if (value[key] != preValue.current[key]) {
obj[key] = value[key];
preValue.current[key] = value[key];
}
});
if (Object.keys(obj)?.length) {
fn(obj);
}
});
return destroyWatch;
}, [preValue, fn, form]);
}
官方useWatch
antd在5.0版本支持类似的api: useWatch
可以替代
https://ant.design/components/form-cn#formusewatch
https://github1s.com/react-component/field-form/blob/master/src/useWatch.ts#L140