我在差异组件中获取5个API。
我给出了3000毫秒的5 API超时,那么我如何在setTimeout进行时设置5组件的加载屏幕,并在setTimout完成时使加载屏幕消失并返回数据。
代码:
function App() {
const [loading, setLoading] = useState(false)
return (
{loading ? <> <Component1 setLoading={setLoading}/>
<Component2/>
<Component3/>
<Component4/>
</> : <LoadingScreen/>
}
)
}
内部组件1代码:
function Component1({setLoading}) {
const [data, setData] = useState([]);
const loadData = async() =>{
const datas = await fetch(`theapi`);
const value = await anime.json()
if (datas.ok) {
setTimeout(() => {
return setData(value.data);
}, 3000);
setLoading(false)
}
}
useEffect(() =>{
loadData();
},[])
return (
<>
{data}
</>
)
}
Btw所有我的组件使用相同的获取方法。感谢的帮助
您可以通过稍微改变状态来实现这一点。代替:
const [loading, setLoading] = useState(false);
do:
const [areFetching, setAreFetching] = useState({
component1: true,
component2: true,
component3: true,
component4: true,
});
每个组件内部:
setTimeout(() => {
return setData(value.data);
}, 3000);
setAreFetching((fetching) => ({ ...fetching, componentNUMBER: false}));
因此,通过这种方式,在您的应用程序组件中添加以下行:
function App() {
const [areFetching, setAreFetching] = useState({
component1: false,
component2: false,
component3: false,
component4: false,
});
const isFetched = Object.values(areFetching).every(fetched => fetched === false);
if (!isFetched) return (<LoadingScreen/>);
return (
<>
<Component1 setLoading={setLoading}/>
<Component2 setLoading={setLoading}/>
<Component3 setLoading={setLoading}/>
<Component4 setLoading={setLoading}/>
</>
)
}