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

G J*_*osh 7 reactjs formik

我正在尝试为我正在处理的项目创建一个编辑页面,但我似乎无法使用来自 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
Run Code Online (Sandbox Code Playgroud)

以下是我的 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"
}]
Run Code Online (Sandbox Code Playgroud)

小智 7

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


atu*_*n23 0

您可以替换检查现有的数据吗:

(data !== undefined)
Run Code Online (Sandbox Code Playgroud)

到:

(data && data.length > 0)
Run Code Online (Sandbox Code Playgroud)