我正在创建一个模块,用户必须在其中上传图像,在等待时,我想设置一个加载状态的覆盖,我有以下代码:
const ModulePage = () => {
const sendData = () => {
//...Send data to firebase
}
return {
<div className="Overlay" /> //I want to display this conditionally while sending
//...
<button onClick={sendData}>Send Module</button>
}
}
我试着使用useState
const ModulePage = () => {
const [isUploading, setIsUploading] = useState(false);
const sendData = () => {
setIsUploading(true)
//...Send data to firebase
setIsUploading(false)
}
return {
{isUploading && <div className="overlay" />}
//...
<button onClick={sendData}>Send Module</button>
}
}
但是没有useEffect是不起作用的,有了useEffect,它在无限循环中运行,如果我这样做:
const ModulePage = () => {
const [isUploading, setIsUploading] = useState(false);
const uploadHandler = () => {
setIsuploading(true);
}
useEffect(() => {
//...Send data to firebase
setIsUploading(false)
}, [isUploading]);
return {
{isUploading && <div className="overlay" />}
//...
<button onClick={uploadHandler}>Send Module</button>
}
}
它从不运行sendData函数
如果发送数据代码是一个承诺,您可以尝试此
const sendData = async () => {
setIsUploading(true)
await //... Send data to firebase
setIsUploading(false)
}
或者这个
const sendData = () => {
setIsUploading(true)
sendDataFunction().then((result) => {
setIsUploading(false)
}).catch((err) => {
setIsUploading(false)
})
}