React Navigation 5 身份验证流程 [英] React Navigation 5 Auth Flow

查看:28
本文介绍了React Navigation 5 身份验证流程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 React Native 应用程序中,我正在使用 React Navigation 5 并尝试将用户路由到身份验证堆栈,如果用户未通过身份验证,即没有 AsyncStorage 中的 access_token.

In my React Native app, I'm using React Navigation 5 and trying to route users to authentication stack if the user is not authenticated i.e. there's no access_token in AsyncStorage.

我感到困惑的是如何从 AsyncStorage 获取令牌,因为它是一个异步过程.我似乎无法在我的 App 组件中 await 调用,即如果我尝试并且不await,它会给我一个错误它,然后我得到一个 promise.

What I'm confused about is how to get the token from AsyncStorage because it's an asynchronous process. I can't seem to await the call in my App component i.e. it gives me an error if I try and if I don't await it, then I get a promise.

我如何使用 React Navigation 5 实现这一点?

How do I implement this using React Navigation 5?

这是我的 App 组件:

const App = () => {

  const authenticatedUser = AsyncStorage.getItem("access_token");
  return (
    <Provider store={store}>
      <NavigationContainer>
        {
          authenticatedUser !== null || typeof authenticatedUser !== "undefined"
          ? <RootNavigator />
          : <AuthNavigator />
        }
      </NavigationContainer>
    </Provider>
  );
};

export default App;

推荐答案

你必须像这样等待从 AsyncStorage 获取令牌.

You have to wait for getting a token from AsyncStorage like this.

const App = () => {

const [loading, setLoading] = usState(true)
const [authenticated, setAuthenticated] = usState(false)

useEffect(()=>{async()=>{
  const authenticatedUser = await AsyncStorage.getItem("access_token");
  setLoading(false)
  if(authenticatedUser !== null) setAuthenticated(true)
 }},[])

  return (
    <Provider store={store}>
      <NavigationContainer>
        { loading &&
         <ActivityIndictor size='small' />
        }
        {
          authenticated && !loading
          ? <RootNavigator />
          : <AuthNavigator />
        }
      </NavigationContainer>
    </Provider>
  );
};

export default App;

这篇关于React Navigation 5 身份验证流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆