如何使用React中的提取功能提交表单数据和文件?

时间:2020-10-16 17:51:15

标签: javascript reactjs fetch form-data

首先,将任务设置为从表单发送数据。该问题已通过以下方式解决:

export let useRequest = () => {
  let request = async (url, method = "Post", body = null, headers = {}) => {
    try {
      if (body) {
        body = JSON.stringify(body);
        headers["Content-Type"] = "application/json";
      }

      let res = await fetch(url, { method, body, headers });
      let data = await res.json();
      return data;
    } catch (e) {
      throw e;
    }
  };

表格:

 <form>
   <input name="name" class="help-input" placeholder="name" type="text" value=""/>
   <input name="email" class="help-input" placeholder="email" type="text" value=""/>
   <textarea name="message" class="help-input"placeholder="message"></textarea> 
   <input name="file" type="file" value="">
   <input name="agree" type="checkbox" value="" checked/>
   <button type="submit" onClick="props.send">send</button>
</form>

表单容器(表单包装器):

export let HelpBlock = (props) => {
  let { request } = useRequest();
  let reqFromForm = async (values) => {
    let data = await request("/api/message", "POST", props.values);
    console.log(data.message)
  };
  return (
    <>
      <Form send={reqFromForm}></Form>
    </>
  );
};

单击按钮后,数据具有以下结构:

{
    name:name,
    email:email,
    message:message,
    file:file
}

1 个答案:

答案 0 :(得分:1)

在这种情况下,我认为您可以根据内容类型渲染正文:

export let useRequest = () => {
  let request = async (url, method = "Post", body = null, headers = {}, contentType="application/json" ) => {
    try {
      if (body) {
        body = renderBodyFormat(body, contentType);
        headers["Content-Type"] = contentType;  
      }

      let res = await fetch(url, { method, body, headers });
      let data = await res.json();
      return data;
    } catch (e) {
      throw e;
    }
  };
  return { request };
};

const renderBodyFormat = (data, type) => {
 const formats = {
   "application/json": ()=> JSON.stringify(body),
   "multipart/form-data": ()=> {
      const form = new FormData();
      Object.keys(data).forEach(key => form.append(key, data[key]));
      return form;
   }
 } 

 return formats[type]();

}

编辑://使用挂钩:

const Component = ()=> {
 const {request} = useRequest();

 useEffect(()=> {
   const data = {
    //...other props
    file: new File(["file"], "file.txt", { type: "text/plain"});
   }

   request(url, "Post", data, {}, "multipart/form-data")
   .then(()=> {
     //...
   })
 })
}

在这里您可以找到更多信息https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch