问题描述
index.js
const handleSubmit = async (value) => {
const formData = new FormData()
for (const file of image.product_img) {
formData.append('product_img',file)
}
formData.append('product_name',value.product_name)
formData.append('category',value.category)
await Axios.post(`https://localhost:3001/add`,formData,{
headers: headers
})
.then(res => {
toast.success('Added Successfully!',{
position: "top-right",hideProgressBar: false,cloSEOnClick: true,pauSEOnHover: true,});
})
.catch(e => {
toast.error('not Added',});
})
setTimeout(function () {
history.push('/')
},1500);
};
const validationSchema = Yup.object({
product_name: Yup.string().trim().required('Product name is required'),category: Yup.string().required('Category is required')
});
const formik = useFormik({
initialValues: request,onSubmit: handleSubmit,validationSchema: validationSchema
});
return (
<>
<ToastContainer />
<form onSubmit={formik.handleSubmit}>
<div className="form-group">
<label htmlFor='product_name'>Product Name:</label>
<input type="text" name="product_name" placeholder="Enter Product Name" className="form-control"
onChange={formik.handleChange} onBlur={formik.handleBlur} />
{
formik.touched.product_name && formik.errors.product_name ? (
<div className='error'> {formik.errors.product_name} </div>
) : null
}
</div>
<div className="form-group">
<label htmlFor='category'>Category:</label>
<select onChange={formik.handleChange} onBlur={formik.handleBlur} className="form-control" name='category' >
<option> -- Please Select -- </option>
{category.map((it) => {
return (
<option key={it.id} value={it.id}> {it.category_name} </option>
)
})}
</select>
{
formik.touched.category && formik.errors.category ? (
<div className='error'> {formik.errors.category} </div>
) : null
}
</div>
<div className="form-group">
<label htmlFor='product_img'>Product Image:</label> <br />
<input type="file" multiple name="product_img" id="product_img" onChange={e => handleImageChange(e)} />
</div>
<button type="submit" className="btn btn-success" disabled={isSubmitting} > Add </button>
</form>
</>
)
};
Formik可以正常工作,但是因为formik不支持图像上传,所以我尝试不带formik来上传图像,并使用formik保留所有表单,当我上传图像时,它可以正常工作,但是当我不上传任何图像时,它给出了错误“无法读取未定义的属性'product_img'”,因为图像字段是可选的。因此,即使没有图像上传,我也希望提交表单。任何帮助都会被申请
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)