【问题标题】:How to change routes when auth status changes in React Native如何在 React Native 中的身份验证状态更改时更改路由
【发布时间】:2020-12-04 12:34:29
【问题描述】:

我需要做的是根据用户身份验证状态呈现反应原生路由。现在我这样做是错误的,通过运行间隔来检查身份验证状态的变化:

import React, { useState, useEffect } from 'react';
import { AppLoading } from 'expo';
import { checkAuth } from './auth';
import { LoggedInRoutes, LoggedOutRoutes } from './router';

export default () => {
  const [isReady, setReady] = useState(false);
  const [loggedIn, setLoggedIn] = useState(false);

  useEffect(() => {
    setInterval(() => {
      checkAuth()
        .then((res) => { setLoggedIn(res); setReady(true); console.log('checked..') })
        .catch((err) => alert(err));
    }, 1500);
  }, [loggedIn]);

  if (!isReady) {
    return (
      <AppLoading
        onFinish={() => setReady(true)}
      />
    );
  }
  return (
    loggedIn ? <LoggedInRoutes /> : <LoggedOutRoutes />
  );
}

但显然这很糟糕。我正在使用异步存储在用户进行身份验证时保存用户,并在他单击注销按钮时将他从存储中删除。

有没有办法检查异步存储的变化并重新渲染路由?或者当用户单击登录/注销按钮时运行更改登录状态的函数?

【问题讨论】:

  • 每次登录状态发生变化时都会重新渲染组件。但是由于您使用的是自定义身份验证系统,我不确定如何解决这个问题!也许你可以设置一个监听器,你能提供验证码吗?
  • 我找到了解决方案。我在路由组件中传递了一个函数作为参数,并在用户通过身份验证时调用它。

标签: react-native expo react-native-navigation


【解决方案1】:

我建议在反应导航中使用 switchNavigator

reactnavigation.org/docs/4.x/auth-flow – mr-nobody 40 秒前编辑删除

【讨论】:

    【解决方案2】:

    这种方法很有效。

    import React, {useState, useEffect} from 'react';
    import OnBoardingRoutes from './onBoarding.routes';
    import AppRoutes from './app.routes';
    import checkFirstUsage from "./checkFirstUsage/path";
    
    
    const Routes: React.FC = () => {
      const [loading, setLoading] = useState(true)
      const [firstUsage,setFirstUsage] =useState(null);
    
      useEffect(() => {
         async function check() {
              const fU = await checkFirstUsage()
              setFirstUsage(fU)
              setLoading(false)
         }
    
         check()
      },[])
    
      if (loading) return null  // or any better component
    
      return firstUsage ? <OnBoardingRoutes /> : <AppRoutes />;
    };
    
    export default Routes;
    

    【讨论】:

      猜你喜欢
      • 2018-11-06
      • 2020-12-08
      • 2016-04-06
      • 1970-01-01
      • 2019-06-01
      • 2021-06-23
      • 2021-01-02
      • 2020-07-13
      • 1970-01-01
      相关资源
      最近更新 更多