React Native Root Element,决定异步调用

React Native Root Element, deciding on async call

我目前正在用 React-Native 编写一个应用程序,其中还包括一个登录。我使用 AsyncStorage 来保存凭据。现在我想向用户显示不同的屏幕(导航器),无论他是否登录。 为了检查他是否登录,我检查 AsyncStorage 中是否有凭据,以及检查此 returns 承诺的函数。所以现在当我在我的组件中调用函数时,它不会等到承诺已经解决并且我不知道如何解决。我试过了,但这也失败了。也许你有什么想法。在我的代码下面。谢谢

import 'react-native-gesture-handler'
import { NavigationContainer } from '@react-navigation/native'
import AppNavigation from './navigation/AppNavigation.js'
import { ThemeProvider, Text } from 'react-native-magnus'
import { useState, useEffect, useCallback, Suspense} from 'react'
import {React } from 'react'
import getNutrientsCompare from './utils/getNutrientsCompare.js'
import getLoginSession from './utils/getLoginSession.js'
import Login from './pages/Login.js'
import { ActivityIndicator } from 'react-native'

const wait = (timeout) => {
    return new Promise(resolve => setTimeout(resolve, timeout));
} 

const RootElement = () => {
    const [result, setResult] = useState(null)
    getLoginSession().then(data => {
        [loginSessionState, setLoginSessionState] = useState("");
        if (loginSessionState != null) {
            setResult((
                <ThemeProvider>
                    <NavigationContainer >
                        <AppNavigation />
                    </NavigationContainer>
                </ThemeProvider>))
        } else {
            setResult((
                <ThemeProvider>
                    <Login>
                    </Login>
                </ThemeProvider>
            ))
        }
    })
    return result
}

    const App = () => {
    return (
        <Suspense fallback={<ActivityIndicator />}>
            <RootElement />
        </Suspense>
    )   
}

export default App

试试这个

import { ActivityIndicator } from "react-native";


const RootElement = () => {
  const [loggedIn, setLoggedIn] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      try {
        const data = await getLoginSession();
        if (data != null) {
          setLoggedIn(true);
        }
      } catch (error) {
        setLoggedIn(false);
      }
      setLoading(false);
    })();
  }, []);

  return (
    <>
      {!loading ? (
        loggedIn ? (
          <ThemeProvider>
            <NavigationContainer>
              <AppNavigation />
            </NavigationContainer>
          </ThemeProvider>
        ) : (
          <ThemeProvider>
            <Login />
          </ThemeProvider>
        )
      ) : (
        <ActivityIndicator size="large" color="#00ff00" />
      )}
    </>
  );
};