我有一个从 api 获取数据的应用程序。获取时有一个加载状态,会在屏幕上显示一个图标。然而,这只是一闪而过。我想在屏幕上显示加载图标 2 秒钟,以改进 UI 并让用户知道正在发生某些事情。
这是我的代码:
const [info, setInfo] = useState({});
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
axios
.get(`https://restcountries.eu/rest/v2/alpha/${code}`)
.then((response) => {
console.log(response);
setInfo(response.data);
setLoading(false);
});
}, []);
return (
<div>
<Link to='/'>
<button>Back</button>
</Link>
{loading ? (
<LoadingIcon />
) : (
<CountryInfo
info={info}
borders={borders}
languages={languages}
currencies={currencies}
/>
)}
</div>
);
};
最佳答案
你可以使用promise.all
因此,即使您的请求提早到来,您的加载也会显示至少 2 秒。
setLoading(true);
const fetchPromise = axios
.get(`https://restcountries.eu/rest/v2/alpha/${code}`);
const timeOutPromise = new Promise(resolve => {
setTimeout(resolve, 2000);
})
Promise.all([fetchPromise, timeOutPromise]).then(([response]) => {
console.log(response);
setInfo(response.data);
setLoading(false);
})
关于javascript - 如何使用钩子(Hook)在 React 中使用 setTimeout() 来实现加载状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59925358/