我正在根据参数中的 id 从我的后端获取数据。通过查看控制台日志可以很好地获取数据,包括不同的值,例如 product.title.
我希望能够使用 formik 编辑我的产品,但由于某种原因,即使一切设置完美,初始值也不会填充到输入字段中。
下面是我使用Effect取数据的代码:
useEffect(() => {
const fetchProductById = async () => {
try {
const response = await axios.get(`http://localhost:3005/product/${prodId}`)
setProduct(response.data)
} catch (err) {
console.error(err)
}
}
fetchProductById();
},[prodId]);
这是我的 formik 初始值(我以 product.title 为例):
const editProductFormik = useFormik({
initialValues: {
title: product.title,
description: '',
price: '',
images: images,
coverImage: coverImage,
location: '',
age: '',
condition: '',
Category: '',
SubCategory : '',
seller : seller,
},
这是我对产品标题的输入:
<Box>
<Input mr={2} width="250px" type="title" value={editProductFormik.values.title} onChange={editProductFormik.handleChange("title")} marginBottom="10px" />
{editProductFormik.touched.title && editProductFormik.errors.title ? (
<Text mt={2} color="red" fontWeight="bold">{editProductFormik.errors.title}</Text>
) : null}
</Box>