如何在react-admin中用API响应更新<TextInput />的值?
在React-admin中更新TextInput的值(从API响应获取)
方法1:正确使用useForm的setValue
确保你在react-admin的表单上下文(如Create、Edit、Form组件内部)调用useForm,并在API请求完成后执行setValue:
import { useForm, TextInput, SaveButton } from 'react-admin'; import { useEffect } from 'react'; const MyForm = () => { const { setValue } = useForm(); useEffect(() => { // 模拟API请求获取更新值 const fetchUpdatedValue = async () => { const response = await fetch('/api/get-updated-value'); const data = await response.json(); // 此处source需与TextInput的source完全匹配 setValue('your-source-name', data.updatedValue); }; fetchUpdatedValue(); }, [setValue]); return ( <> <TextInput source="your-source-name" label="输入框标签" /> <SaveButton /> </> ); };
若之前调用setValue无效,大概率是以下原因:
- 未在表单上下文内调用
useForm(比如在Create/Edit外部,或未用Form组件包裹) setValue的source参数与TextInput的source拼写、大小写不匹配- 调用时机错误,比如组件未初始化或API请求未完成时就执行
方法2:通过Form组件的defaultValues初始化值
如果需要在表单加载时就从API获取初始值,可先请求数据再传递给defaultValues:
import { Form, TextInput, SaveButton } from 'react-admin'; import { useEffect, useState } from 'react'; const MyForm = () => { const [initialValues, setInitialValues] = useState({}); useEffect(() => { const fetchInitialData = async () => { const response = await fetch('/api/get-initial-data'); const data = await response.json(); setInitialValues({ 'your-source-name': data.updatedValue }); }; fetchInitialData(); }, []); return ( <Form defaultValues={initialValues}> <TextInput source="your-source-name" label="输入框标签" /> <SaveButton /> </Form> ); };
方法3:结合useQuery与useForm
如果使用react-admin的数据提供者接口,可通过useQuery获取数据后更新表单:
import { useForm, TextInput, SaveButton, useQuery } from 'react-admin'; const MyForm = () => { const { setValue } = useForm(); // 调用数据提供者的getOne方法获取资源数据 const { data, isLoading } = useQuery({ type: 'getOne', resource: 'your-resource', payload: { id: '123' } }); useEffect(() => { if (data) { setValue('your-source-name', data.targetField); } }, [data, setValue]); if (isLoading) return <div>加载中...</div>; return ( <> <TextInput source="your-source-name" label="输入框标签" /> <SaveButton /> </> ); };
关键注意事项
- 所有操作必须在react-admin的表单上下文内进行,Create、Edit组件已自带Form上下文,其子组件可直接使用
useForm - 自定义表单必须用Form组件包裹,否则
useForm无法获取表单上下文 setValue的source参数需与TextInput的source完全一致,不能有拼写或大小写错误
内容的提问来源于stack exchange,提问作者Aliaas
相关产品推荐
相关产品推荐

