【问题标题】:How to use Async Await in "onDrop" of "react-dropzone" ? (Parsing error: Can not use keyword 'await' outside an Async function)如何在“react-dropzone”的“onDrop”中使用异步等待? (解析错误:不能在异步函数之外使用关键字'await')
【发布时间】:2020-02-17 22:06:13
【问题描述】:

我正在使用“react-dropzone”来删除文件:

import React from "react";
import { useDropzone } from "react-dropzone";

const DropzoneUpload = ({ onDrop, accept }) => {
  // Initializing useDropzone hooks with options
  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept
  });


  return (
    <div {...getRootProps()}>
      <input className="dropzone-input" {...getInputProps()} />
      <div className="text-center">
        {isDragActive ? (
          <p className="dropzone-content">Release to drop the files here</p>
        ) : (
          <p className="dropzone-content">
            Drag 'n' drop some files here, or click to select files
          </p>
        )}
      </div>
    </div>
  );
};

export default DropzoneUpload;

它在 App.js 中是这样使用的:

<DropzoneUpload
        onDrop={onDrop}
        accept={
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
        }
      />

onDrop 函数在哪里:

const onDrop = useCallback(async acceptedFiles => {
    // this callback will be called after files get dropped, we will get the acceptedFiles. If you want, you can even access the rejected files too
    console.log(acceptedFiles);
    const axiosInstance = axios.create({
      baseURL: "http://localhost:5000"
    });

    const reader = new FileReader();
    reader.onabort = () => console.log("file reading was aborted");
    reader.onerror = () => console.log("file reading has failed");
    reader.onload = () => {
      // Do whatever you want with the file contents
      const binaryStr = reader.result;
      const body = JSON.stringify({
        binaryStr
      });
      await axiosInstance.post("/api/upload", body);
    };

    acceptedFiles.forEach(file => reader.readAsArrayBuffer(file));
  }, []);

问题:当我将Async Await 添加到回调函数onDrop 时,我得到: Parsing error: Can not use keyword 'await' outside an Async function

那么我该如何等待服务器的答复呢?

【问题讨论】:

    标签: reactjs asynchronous async-await dropzone react-dropzone


    【解决方案1】:
    // you forgot add async keyword here 
    reader.onload = async () => {
      const binaryStr = reader.result;
      const body = JSON.stringify({
        binaryStr
      });
      await axiosInstance.post("/api/upload", body);
    };
    

    您也可以在useCallback(async... 处删除顶级async

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      相关资源
      最近更新 更多