gpt4 book ai didi

reactjs - REACT - 从 API 获取后在 Formik 表单中设置初始数据

转载 作者:行者123 更新时间:2023-12-04 04:07:55 25 4
gpt4 key购买 nike

我正在尝试为我正在处理的项目做一个编辑页面,我似乎无法让表单填写来自我的 API 的初始值。我希望在我从我的 REST API 获取数据后,它会被设置为我的表单字段的初始值,但是,它看起来并没有发生。我可以做些什么来实现我的目标,即根据我从 API 获得的值预先填充我的表单字段?

这是我的代码:

const EditBookInfoForm= (properties) => {
const [data, setData] = useState();

useEffect(() => {
fetch(apiUrl + properties.bookId)
.then(response => response.json())
.then(result => {
setData(result);
});
}, []);

const validationSchema = Yup.object().shape({
title: Yup.string()
.max(50, 'You may only enter up to 50 characters')
.required('Required'),
description: Yup.string()
.max(200, 'You may only enter up to 200 characters')
.required('Required'),
author: Yup.string()
.required('Required')
})

return (
<div>
{
(data !== undefined) ?
<Formik initialValues={data}
validationSchema={validationSchema}
onSubmit={(values) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
}, 3000)
}}
>
{props => (
<Form>
<Grid container spacing={2}>
<Grid item xs={6}>
<TextField name="bookId" label="Book ID" variant="outlined"
margin="dense" color="secondary" type="input"/>
<TextField name="title" label="Title" variant="outlined"
margin="dense" color="secondary" type="input"/>
<TextField name="description" label="Description" type="input"
variant="outlined" margin="dense" color="secondary" />
<TextField name="author" label="Author" variant="outlined"
margin="dense" color="secondary" type="input"/>
</Grid>
</Grid>
<DialogActions >
<DangerButton icon={<SaveRecordIcon />} label="Save"
handleClick={() => alert("Save")} />
<PrimaryButton icon={<PlusIcon />} label="Submit"
handleClick={() => props.handleSubmit()} />
<NeutralButton label="Next" handleClick={() => alert("next")} />
</DialogActions>
</Form>
)}
</Formik>
: <OverlaySpinner />
}
</div >
)
}

export default EditBookInfoForm

以下是我的 API 的结果:
[{
bookId: 1
title: "Anna Karenina"
description: "Anna Karenina tells of the doomed love affair between the sensuous and rebellious Anna and the dashing officer, Count Vronsky."
author: "Leo Tolstoy"
}]

最佳答案

您可以在 Formik 中设置属性 'enableReinitialize={true}',如以下主题 Recommended way to set initialValues from async api call #1033 所示

关于reactjs - REACT - 从 API 获取后在 Formik 表单中设置初始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62210716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com