【问题标题】:Formik initialValues not getting updated for fileFormik initialValues 未更新文件
【发布时间】:2021-01-19 04:43:59
【问题描述】:

我的表单中有 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"

。如何解决?

【问题讨论】:

    标签: reactjs file-upload formik


    【解决方案1】:

    根据官方文档,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 个参数 event =&gt;"photo", setFieldValue(event.target.files[0]
    • 哦,我用错误的代码编辑了问题。
    【解决方案2】:

    我的解决方案是在每个字段后面加上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);
                            }}
    >
    

    如果有人想重构这个,请这样做,我知道代码很乱。

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 2020-07-22
      • 2016-12-17
      • 1970-01-01
      相关资源
      最近更新 更多