我想首先显示一个加载器,在加载器根据条件手动关闭一段时间后,我想显示一个函数或显示一个标题1。
我想当最初当页面加载时,加载器应该显示,但在一段时间后,它可能会在setTimeout的帮助下关闭,如果数组(videoid)的长度为0,我想显示标题"在集合中输入至少一个视频";否则,如果长度不为零,则运行fetchFunc()并显示结果,从而渲染组件。
我尝试使用承诺,但"首先输入至少一个视频";在页面加载时已经被渲染。我怎样才能实现它?
const [display, setdisplay] = useState();
const [userMsg, setuserMsg] = useState(true);
useEffect(() => {
displayFunc();
}, []);
function displayFunc() {
new Promise(function (myResolve) {
myResolve(
setTimeout(() => {
setuserMsg(false);
}, 2000)
);
}).then(() => {
if (videoIds.length === 0) {
setdisplay(false);
} else {
fetchFunc();
setTimeout(() => {
setdisplay(true);
}, 2000);
}
});
}
{userMsg && <Loading />}
{display ? (
<ExploreCard videoArray={videoArray} explVidFunc={explVidFunc} />
) : (
<h1>Enter at least one video in collection first</h1>
)}
export const View = () => {
const [videos, setVideos] = useState([]);
const fetch = async () => {
// fetch logic here
setVideos(); // put response or data here
});
useEffect(() => {
/*
I don't believe the timeout is necessary, but if you want to
delay the fetch function, you can do something like the following.
setTimeout(() => fetch(), 3000);
*/
fetch();
}, [videos]);
return (
<>
{!!videos.length && <Loading />}
{!videos.length ? (
<ExploreCard
{/* explVidFunc={explVidFunc */}
videoArray={videoArray}
/>
) : (
<h1>Enter at least one video in collection first</h1>
)}
</>
);
}:
const [loading, setLoading] = useState(false)
const [videos, setVideos] = useState([])
const fetchVideos = async () => {
try{
// call api to fetch videos
const res = callApi()
setLoading(false)
// change according to you response
setVideos(res.data)
} catch{
setLoading(false)
}
}
useEffect(() => {
fetchVideos()
},[])
现在,您可以检查加载情况。如果为真,show Loader else,检查是否有视频。如果它的长度为零,则显示某个分量,否则显示不同分量。