如何在Expo Splashscreen中调用API?
我是React Native的新手,所以我不知道如何在React -Native应用程序中添加api调用。上下文 - 我正在构建一个反应本地的应用EXPO,在应用程序加载上应将API发送到后端以获取订单数据,并且基于该数据,我要么显示屏幕A(已交付)或B(订单在路上)。当应用程序仍然加载时,我想将此API调用添加到SplashScreen中,因此当应用程序加载时,获取API数据并显示屏幕A/B时没有延迟。 我有一个简单的用法函数可以像这样调用API:
const [data, setData] = useState{[]}
useEffect(() => {
const getData = async () => {
try {
const response = await axios.get(url);
if (response.status.code === 200 ) {
setData (response.data) // to save data in useState
}
} else if (response.status.code != 200) {
throw new Error();
}
} catch (error) {
console.log(error);
}
};
getData();
}, []);
然后在返回中:
if (data.order.delivered) {
return <ScreenA />
}
else if (!data.order.delivered) {
return <ScreenB />
else {return <ScreenC />}
问题是,有时如果API慢,则在Splash屏幕应用程序具有白色屏幕之后,或者可以看到屏幕。在应用程序加载并具有更好的UX时,如何在SplashScreen中调用API?
I'm new in react native so I can't figure out how to add an API call inside SplashScreen in react -native app. The context - I'm building a react-native app expo, which on app load should send API GET request to the backend to get order data, and based on that data I'm either displaying screen A(delivered) or B(order on it's way). I want to add this API call inside the SplashScreen when app still loads so when app is loaded there is no delay in getting API data and displaying screen A/B.
I have a simple useEffect function to call API like this:
const [data, setData] = useState{[]}
useEffect(() => {
const getData = async () => {
try {
const response = await axios.get(url);
if (response.status.code === 200 ) {
setData (response.data) // to save data in useState
}
} else if (response.status.code != 200) {
throw new Error();
}
} catch (error) {
console.log(error);
}
};
getData();
}, []);
and then in the return:
if (data.order.delivered) {
return <ScreenA />
}
else if (!data.order.delivered) {
return <ScreenB />
else {return <ScreenC />}
The issue is that sometimes if API is slow, then after splash screen app has a white screen, or ScreenC can be seen. How can I call API in the splashscreen while app is loading and have a nicer ux?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用简单的Usestate进行自定义挂钩,并在获取数据后将其放置
,然后,您可以在app.js文件的顶部使用简单的if语句
像这样
you can make a custom hook with simple UseState and put it after you've fetched your data
and After that, you can use a Simple If statement on top of your app.js file
like this
您可以使用expo
expo-splash-screen
实现此目标:在Mount上调用此挂钩...
您也可以检查expo doc
you can use expo
expo-splash-screen
to achieve this goal:call this hook on mount...
you can also check expo doc