React-Admin中使用react-hook-form设置表单值如何避免更新警告
解决React-Admin中useFormContext设置默认值触发警告的问题
你遇到的警告是因为在组件渲染阶段直接调用formContext.setValue,这会导致Form组件在MyInput渲染过程中触发状态更新,违反了React的渲染规则(不允许在一个组件渲染时更新另一个组件的状态)。
方法一:用useEffect延迟设置默认值
把setValue放到useEffect中执行,确保代码在组件挂载完成后运行,而非渲染期间:
... import { Create, SimpleForm, SelectInput } from 'react-admin'; import { useFormContext, useEffect } from 'react-hook-form'; const MyInput = () => { const formContext = useFormContext(); useEffect(() => { // 仅在组件挂载时设置一次默认值 formContext.setValue('category', 'tech'); }, [formContext]); // 依赖formContext确保引用有效 return ( <SelectInput source="category" choices={[ { id: 'tech', name: 'Tech' }, { id: 'people', name: 'People' }, ]} /> ); }; ... const ItemCreate = () => { return ( <Create> <SimpleForm> <MyInput /> </SimpleForm> </Create> ); }; ...
如果需要避免重复设置(比如表单重置后不需要再覆盖),可以先检查当前字段值:
useEffect(() => { const currentValue = formContext.getValues('category'); if (!currentValue) { formContext.setValue('category', 'tech'); } }, [formContext]);
方法二:直接用SimpleForm的initialValues属性
如果你的默认值是静态的,不需要动态计算,更简洁的方式是直接给SimpleForm传递initialValues属性,完全不需要自定义组件:
const ItemCreate = () => { return ( <Create> <SimpleForm initialValues={{ category: 'tech' }}> <SelectInput source="category" choices={[ { id: 'tech', name: 'Tech' }, { id: 'people', name: 'People' }, ]} /> </SimpleForm> </Create> ); };
这种方式更符合React-Admin的设计规范,也不会触发任何警告。
内容的提问来源于stack exchange,提问作者Woodchuck
相关产品推荐
相关产品推荐

