我有一个页面,它在加载时会执行一些很重的API调用,收集所有数据大约需要5-7秒。我引用了[this question],并决定添加一个带有setTimeout的加载器,以模拟附加的"API调用“,并在加载器和不加载器的情况下定时加载时间。
如果没有装载机,它需要- 6.92秒
装载机花了- 14.05秒
这是我的密码:
const [loading, setLoading] = useState(false);
useEffect(() => {
async function updateUI() {
const ethers_owner = await administrativeSidechainContract.owner()
setContractOwner(() => {
return {contractOwner: ethers_owner.toLowerCase()}})
const ethers_matchCountMessage = await administrativeSidechainContract.matchCount()
setMatchCount(() => {
return {matchCount: ethers_matchCountMessage,}})
}
updateUI()
//here is the loader simulation
setLoading(true);
setTimeout(() => {
setLoading(false);
}, 7000);
}, [])
return (
<>
{loading ?
<div className="loader-container"></div> :
<div className="decks-container"></div>}
</>
)从我的测试来看,不管我设置了多少setTimeout,加载程序似乎只会增加页面加载时间。
如何使数据加载时间与setTimeout时间重叠而不是相互重叠?
谢谢你提前给我时间!
发布于 2022-09-19 00:44:19
我想你不需要setTimeout。相反,您可以这样做:
以下是一个例子:
useEffect(() => {
const res = [];
async function updateUI() {
await Promise.all([
administrativeSidechainContract.owner(),
administrativeSidechainContract.matchCount()
])
.then(results => {
res.push(results)
});
const ethers_owner = res[0];
const ethers_matchCountMessage = res[1];
// you may set loader to false here
setLoading(false);
setContractOwner(() => {
return {contractOwner: ethers_owner.toLowerCase()}})
setMatchCount(() => {
return {matchCount: ethers_matchCountMessage,}})
}
setLoading(true);
await updateUI();
// If you don't want to setLoading(false) inside updateUI method, you may set loader to false here
}, [])https://stackoverflow.com/questions/73767177
复制相似问题