如何在使用reactjs执行submit方法时一次发布2个API?

如何在使用reactjs执行submit方法时一次发布2个API?,reactjs,Reactjs,我是新手,我正在做一个小项目,我已经创建了一个表单,我还想添加一个文件。表单具有一个API,用于上载具有另一个API的文件 handleSubmit = e => { e.preventDefault(); const { firstName, LastName, phoneNumber} = this.state; const data = { firstName, lastName, phoneNumber }; a

我是新手,我正在做一个小项目,我已经创建了一个表单,我还想添加一个文件。表单具有一个API,用于上载具有另一个API的文件

 handleSubmit = e => {
    e.preventDefault();
    const { firstName, LastName, phoneNumber} = this.state;
    const data = {
      firstName,
      lastName,
      phoneNumber
    };
axios.post(`/api/Form`, data, {
        headers: { 'Content-Type': 'application/json' }
      })
        .then(res => {
          console.log(res)
          console.log(res.data);
        })
        .catch((err) => {
          console.log(err)
        })
对于文件:

 uploadFile = (files) => {

    var formData = new FormData();

    files.map((file, index) => {
      formData.append(`file${index}`, file);
    });
fetch('/api/uploadFiles', {
       method: 'POST',
       body: formData,
     })
      .then(response => response.json())
      .then(success => {

       })
       .catch(error => console.log(error)
       );
  }


我无法理解如何在submit方法中编写这两个API。有人能帮我解答这个问题吗?我不知道如何在submit方法中提供2个API。

将formData分配给State

uploadFile = (files) => {
    var formData = new FormData();
    files.map((file, index) => {
      formData.append(`file${index}`, file);
    });
    this.setState({file:formData});
}
然后在handleSubmit中发布2个API

handleSubmit = e => {
    e.preventDefault();
    const { firstName, lastName, phoneNumber, file} = this.state;
    const data = {
      firstName,
      lastName,
      phoneNumber
    };
    axios.post(`/api/Form`, data, {
        headers: { 'Content-Type': 'application/json' }
    }).then(res => {
       console.log(res)
       console.log(res.data);
    }).catch((err) => {
       console.log(err)
    });
    if(file) {
       fetch('/api/uploadFiles', {
          method: 'POST',
          body: file,
       }).then(response => response.json()).catch(error => console.log(error));
    }
}

在两个不同的函数中调用这些api,您可以在
handleSubmit
submit方法中调用这两个函数。。然后最终可以使用
Promise.all
获得结果。。这个或类似的东西应该对你有帮助。谢谢。这个解决方案非常有效!。谢谢你解决了我的问题。我还有一个问题。是的Sandhya告诉我你的问题如果我们没有任何文件上传的API,那么我们如何处理和提交表单中的文件。你能帮助我吗?检查文件是否有使用if条件的数据。如果文件有任何内容,则调用上载API。如果您没有任何上传API,则无需传递文件。检查更新的我们没有任何上传api那么我们如何上传