我正在渲染一个使用状态来存储数据的页面,它包含几个需要异步/等待的事件处理程序,因为它包含获取函数。我该怎么办?
我已经阅读过有关使用 useEffect 的内容,但在这种情况下如何将其集成到处理程序中?可以吗?
这是我的 page.jsx 文件之一的片段:
"use client";
import { useState } from "react";
const CarouselSectionPage = () => {
const [file, setFile] = useState();
const [uploading, setUploading] = useState(false);
const handleFileChange = (e) => {
if (e.target.files) {
const image = e.target.files[0];
new Compressor(image, {
quality: 0.6, // 0.6 can also be used, but its not recommended to go below.
success: (compressedResult) => {
setCompressedFile(compressedResult);
setFile(compressedResult);
},
});
}
};
const handleUploadClick = async() => {
if (!compressedFile) {
return;
}
try {
setUploading(true);
await createCarousel({
variables: {
input: {
image: {
bucket: "testbucket",
key: secret.key,
region: "us-1",
},
),
},
},
});
setUploading(false);
setTimeout(() => {
navigate(0);
}, 2000);
} catch (error) {
console.log("Error uploading file: ", error);
}
};
return (
<div>
<input
type="file"
id="images"
accept="image/*"
onChange={handleFileChange}
required
style={{ display: "none" }}
/>
<button disabled={uploading} onClick={() => handleUploadClick()}>
</div>
)
};
上面的代码当然不起作用,因为“使用客户端”和 async/await 会相互冲突。感谢所有意见!
提前谢谢您!
如果你想在
async/await
中实现useEffect
,请像这样。 useEffect
本身只接受普通回调,没有async
。
useEffect(() => {
const yourFetch = async() => {
const res = await fetch(xxxx)
// Do something to res.
}
yourFetch();
}, [Deps])
// Deps depend on you. If you want to run at only first render, empty the array.