使用react-hook-form的Controller时出现path.split is not a function报错
问题根因
TypeError: path.split is not a function错误来自react-hook-form v7版本的setValueAPI调用不符合规范:v7的setValue不支持直接传入对象批量设置多个字段值,第一个入参要求是单个字段名字符串,传入对象会触发split方法调用报错。useFormContext解构报错是因为当前组件的上层父组件没有包裹<FormProvider />组件注入表单上下文。
修复方案
1. 修正赋值逻辑
如果要设置默认值,优先推荐在useForm初始化时通过defaultValues配置,无需额外触发useEffect:
const { control, handleSubmit, setValue } = useForm({ defaultValues: { Short_description: "Subject", Supplier_Name: "Sender" } });
如果确实需要异步/后续触发批量赋值,可以用reset方法,或者多次调用setValue:
// reset批量赋值 useEffect(() => { reset({ Short_description: "Subject", Supplier_Name: "Sender" }); }, [reset]); // 多次调用setValue单字段赋值 useEffect(() => { setValue("Short_description", "Subject"); setValue("Supplier_Name", "Sender"); }, [setValue]);
2. 补全Controller的属性绑定
当前Controller的render回调只提取了value传给TextField,缺少onChange、onBlur等表单事件绑定,会导致输入内容无法同步到表单状态,修正后的写法:
return( <> <Controller render={({ field }) => ( <TextField fullWidth {...field} /> )} name="Supplier_Name" control={control} /> <Controller render={({ field }) => ( <TextField fullWidth {...field} /> )} name="Short_description" control={control} /> </> );
3. useFormContext适配方案
如果要使用useFormContext,需要在上层父组件先注入表单实例:
// 上层父组件 import { FormProvider, useForm } from 'react-hook-form'; const FormWrapper = () => { const formMethods = useForm({ defaultValues: { Short_description: "Subject", Supplier_Name: "Sender" } }); return ( <FormProvider {...formMethods}> {/* 你的表单子组件 */} </FormProvider> ) }
完成上层注入后,子组件内就可以正常解构useFormContext的返回值。
内容的提问来源于stack exchange,提问作者Suvesh
相关产品推荐
相关产品推荐

