React - 前端组件提交处理程序调用 API 函数进行获取,但不等待返回值

问题描述 投票:0回答:1

我有一个用于表单提交的处理程序,它获取用户图像,将其发送到后面,对该图像执行操作,然后将修改后的图像(作为 base64)返回到前面进行显示。

从背面发送和接收图像效果很好。但是在前端API中接收到图像后,我无法将其交给前端组件,因为组件处理程序没有等待前端API返回。

具有表单和处理程序的组件:

function Workshop() {

  // Used to store and update the front when data are modified
  const [imageUpload, setImageUpload] = useState(); 
  const [imageGenerated, setImageGenerated] = useState();

  // Handle the submit of the form
  const handleSubmit = event => {
    event.preventDefault();

    // Append the user image to the formData object
    setImageUpload(event.target.files[0]);
    const formData = new FormData();
    formData.append("file", imageUpload);

    // Calls the FrontEnd API with the image to be modified
    if(imageUpload) {
      const res = frontAPI.callGenerateImage(formData);
      console.log("back to front"); // ### THIS IS WHERE IT DOESNT WORK ###
      console.log(res); // ### THIS IS WHERE IT DOESNT WORK ###
      setImageGenerated(res); // ### THIS IS WHERE IT DOESNT WORK ###
    }
  };

  return (                                                                                                                                                                                                                                                                                                                                        
    <>
      <div className="workshop">
        <form method="post" onSubmit={handleSubmit} encType="multipart/form-data">
            <input type="file" name="imageUploader" onChange={handleImagePreview} />
            <img alt="preview image" src={imagePreview} />
            <button type="submit">Modify Image</button>
        </form>
        <img alt="generated image" src={"data:image/jpeg;base64," + imageGenerated} />
      </div>
    </>
  );
}

export default Workshop;

FrontEnd API 与 fetch :

export function callGenerateImage(formData) {
  var  base64;
  fetch("/generator", {
    method: "POST",
    body: formData
  })
  .then(data => data.json())
  .then(res => {
    base64 = Buffer.from(res.data, "binary" ).toString("base64");
    console.log(base64); // THIS IS THE BASE64 STRING IN THE OUPUT BELOW
    return base64;
  })
};

输出:

enter image description here

正如您所看到的,我确实收到了修改后的图像的 Base64 流,但是

const res = fontAPI.callGenerateImage(formData);
行不会等待获取的实际返回,而是继续
console.log("back to front");
.

我尝试将 API 函数切换为异步函数并进行更改

const res = frontAPI.callGenerateImage(formData);

const res = await frontAPI.callGenerateImage(formData);

但是它不起作用,因为我不在顶层,即使我删除了“if”,因为我处于组件的函数中。

我相当确定答案非常简单,但我不明白。

非常感谢您的帮助!

reactjs asynchronous async-await fetch top-level-await
1个回答
0
投票

在提交函数中使用 async/await 即可得到结果。

const handleSubmit = async (event) => {
    event.preventDefault()

    const file = event.target.files[0];

    if (file) {
        const formData = new FormData();
        formData.append("file", file);

        const res = await frontAPI.callGenerateImage(formData);
        setImageGenerated(res);
    }
}

此外,您不应该在同一函数中设置状态然后检查状态值。当您运行 setImageUpload() 然后检查 if (imageUpload) 时,直到下次调用提交函数时您才会获得更新的状态。相反,像我一样将其设置为变量。

© www.soinside.com 2019 - 2024. All rights reserved.