我正在使用“ 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
那么我该如何等待服务器的答复?
答案 0 :(得分:2)
// you forgot add async keyword here
reader.onload = async () => {
const binaryStr = reader.result;
const body = JSON.stringify({
binaryStr
});
await axiosInstance.post("/api/upload", body);
};
您还可以在async
处删除顶级useCallback(async...
。