我正在嘗試實作一個 React Native 應用程式,如果 isLoading = true,應用程式顯示啟動螢屏,如果 isLoading = false 和 isAuthenticated = false 應用程式顯示身份驗證螢屏,如果 isLoading = false 和 isAuthenticated = true 應用程式顯示主螢屏。
// Splash screen while app loading
if (isLoading) screens = (<><SplashScreen /></>);
// Authentication screens while user not authenticated
else if (!isLoading && !isAuthenticated)
screens = (
<>
<Stack.Screen
name="Register"
component={RegisterScreen}
options={{ animationEnabled: false }}
/>
<Stack.Screen
name="Login"
component={LoginScreen}
options={{ animationEnabled: false }}
/>
</>
);
// All other screens while user authenticated and onboarded
else
screens = (
<>
<Stack.Screen name="Home" component={TabNavigator} />
<Stack.Screen name="Product" component={ProductScreen} />
</>
);
現在我擁有它,以便在應用程式啟動時(在 Navigation.js 中)我在 5 秒后設定超時,并回呼 setIsAuthenticated(false) 和 setIsLoading(false),提示應用程式導航到身份驗證頁面。否則,如果用戶通過身份驗證(使用 onAuthStateChanged 檢查),我將導航到主頁。
useEffect(() => {
const timeout = setTimeout(() => {
setIsAuthenticated(false);
setIsLoading(false);
}, 5000);
setTimer(timeout);
return () => clearTimeout(timer);
}, []);
只要我在導航到正確的頁面時在 5 秒內 (onAuthStateChanged) 獲得身份驗證資訊,這就會很好地作業。但是,在某些情況下,網路非常慢,因此在更新身份驗證狀態之前呼叫了 Timeout 的回呼。在這種情況下,由于呼叫了回呼,我首先導航到身份驗證螢屏,然后在用戶通過身份驗證后立即導航到主頁。
這似乎不是一個非常健壯的方法,所以我想知道是否有更好的方法來處理這種身份驗證方法?
uj5u.com熱心網友回復:
你可以基于你的onAuthStateChanged監聽器和狀態管理來做任何事情。在路由器檔案中創建一個處理用戶物件的狀態,并在身份驗證狀態偵聽器中根據來自onAuthStateChanged的??初始回應設定物件的狀態。這樣,如果偵聽器回傳 null(無身份驗證用戶),您可以將導航器的初始路由設定為登錄,否則進入應用程式內部。為了實作加載器,您可以在路由器中創建另一個名為 isLoading 的狀態,并從一開始就將其設定為 true。一旦 auth listener 回傳結果,無論是 null 還是 user 物件,都將 isLoading 的狀態更改為 false。使用該狀態,您可以在導航器回傳之前回傳加載器視圖。它想與此類似
const [loading,setLoading] = useState(true)
//here goes the abovementioned logic of setting the loading
if(loading){
return <LoaderComponent/>}
return <Navigator/>
uj5u.com熱心網友回復:
認證api成功時請更改狀態。
const [isAuthenticated,setIsAuthenticated] = useState(false);
...
useEffect(() => {
authAPiCall.then(() => {
setIsAuthenticated(true);
})
const timeout = setTimeout(() => {
setIsLoading(false);
}, 5000);
setTimer(timeout);
return () => clearTimeout(timer);
}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/453916.html
