我的表单中有 2 个文件上传,即带有 initialValues
的 Formik 表单
const initialValues = {
coverPhoto: this.props.response.response.coverPhoto
? this.props.response.response.coverPhoto
: {},
photo: this.props.response.response.photo
? this.props.response.response.photo
: {}
};
和表格
<Formik initialValues={initialValues} onSubmit={fields => { this.props.onUpdateMyProfile(fields); }>
....
<input type="file" className="custom-file-input" id="photo" name="photo" accept="image/*" onChange={event => setFieldValue( "photo", event.currentTarget.files[0])}/>
<input type="file" className="custom-file-input" id="coverPhoto" name="coverPhoto" accept="image/*" onChange={event =>"coverPhoto", setFieldValue(event.target.files[0])} />
但是当我提交表单时,它让我获得了 {}
一个空对象而不是文件对象,但是当我控制台出来时,我得到了整个对象以及图像对象。
aboutYourself: "e4 e5 c4"
coverPhoto: ""
firstName: "Yash"
lastName: "Karanke"
photo: File
lastModified: 1605275591390
lastModifiedDate: Fri Nov 13 2020 19:23:11 GMT+0530 (India Standard Time) {}
name: "pngtree-abstract-background-image_88872.jpg"
size: 636889
type: "image/jpeg"
webkitRelativePath: ""
__proto__: File
slug: "yash-karanke"
。我该如何解决?
答案 0 :(得分:0)
根据官方文档,setFieldsValue
需要 2 个参数字段和值。
setFieldValue: (field: string, value: any, shouldValidate?: boolean) => 无效
<input type="file"
className="custom-file-input"
id="photo"
name="photo"
accept="image/*"
onChange={event => setFieldValue("photo",event.target.files[0])} />
答案 1 :(得分:0)
我的解决方案是在每个字段后附加 FormData()
<Formik initialValues={initialValues} onSubmit={fields => {
let data = new FormData();
data.append("photo", fields.photo);
data.append("coverPhoto", fields.coverPhoto);
data.append("firstName", fields.firstName);
data.append("lastName", fields.lastName);
data.append("email", fields.email);
data.append("phoneNumber", fields.phoneNumber);
data.append("zipcode", fields.zipcode);
data.append("userLocation", fields.userLocation);
data.append("aboutYourself", fields.aboutYourself);
this.props.onUpdateMyProfile(data);
}}
>
如果有人想重构这个,请这样做,我知道代码很乱。