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

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

问题描述

我似乎无法在我的 App.js 文件中使用三元身份验证.我正在检查是否有密钥,然后根据该密钥的存在显示 AuthStack 或 MainStack.当我从 AuthStack 转到 MainStack(将密钥设置为 AsyncStorage)时,我收到错误消息 - 任何导航器都未处理带有 payload{'name':'Home'} 的操作NAVIGATE".当我注销或删除密钥时也会发生同样的情况.

I cant seem to get the ternary authentication working on my App.js file. I'm checking to see if there is a key, then displaying either an AuthStack or a MainStack based on the presence of that key. When I go from AuthStack to MainStack (setting a key to AsyncStorage), then I get the error - The action 'NAVIGATE' with payload{'name':'Home'} was not handled by any navigator. The same happens when I Logout or remove the key.

根据文档,用户在通过身份验证后似乎会立即导航到应用程序,但这似乎不起作用.

Based on the documentation, it seemed like the user would immediately navigate into the app when authenticated, but that doesnt seem to be working.

App.js 文件

import React, { useState, useEffect } from 'react';
import AsyncStorage from '@react-native-community/async-storage';

import { NavigationContainer } from '@react-navigation/native';
import AuthStack from './src/navigation/AuthStack'
import MainStack from './src/navigation/MainStack'

export default function App({ navigation }) {
  const [userKey, setUserKey] = useState(null)

  useEffect(() => {
    const bootstrapAsync = async () => {

      try {
        let userKey = await AsyncStorage.getItem('userKey')
        setUserKey(userKey)

      } catch (e) {
        // Restoring token failed
      }

    }

    bootstrapAsync()
  }, [])

  return (
    <NavigationContainer >
      {userKey == null ? (
        <AuthStack />
      ) : (
          <MainStack />
        )}
    </NavigationContainer>
  );
}

验证栈

function AuthStack() {
    return (
        <Stack.Navigator>
            <Stack.Screen name="Login" component={LoginScreen} />
            <Stack.Screen name="ForgotPassword" component={ForgotPasswordScreen} />
            <Stack.Screen name="SignUp" component={SignUpScreen} />
        </Stack.Navigator>
    )
}

export default AuthStack

主栈

function MainStack({ navigation, route }) {
    return (
        <Stack.Navigator>
            <Stack.Screen name='Home' component={HomeScreen} />
        </Stack.Navigator>
    )
}

export default MainStack

推荐答案

这是使用 react-navigation v5 的最小身份验证设置.

Here is a minimal auth setup using react-navigation v5.

import * as React from 'react';

import { Text, View, StyleSheet } from 'react-native';

import { Button, TextInput } from 'react-native-paper';

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import Constants from 'expo-constants';

const Stack = createStackNavigator();

const Auth = React.createContext(null);

export function Login() {
  const [email, setEmail] = React.useState('');
  const [pass, setPass] = React.useState('');
  
  const { setToken } = React.useContext(Auth)

  return (
    <View style={styles.container}>
      <TextInput
        label="Email"
        value={email}
        style={styles.input}
        onChangeText={(t) => setEmail(t)}
      />

      <TextInput
        label="Password"
        value={pass}
        style={styles.input}
        onChangeText={(t) => setPass(t)}
      />

      <Button mode="contained" onPress={() => setToken('Get the token and save!')}>Submit</Button>
    </View>
  );
}

export function Home() {
const { setToken } = React.useContext(Auth)

  return (
    <View>
      <Text>Home</Text>
      <Button mode="contained" onPress={() => setToken(null)}>Signout</Button>
    </View>
  );
}

export default function App() {
  const [token, setToken] = React.useState(null);

  return (
    <Auth.Provider value={{token, setToken}}>
      <NavigationContainer>
        <Stack.Navigator>
          {!token ? (
            <Stack.Screen name="Login" component={Login} />
          ) : (
            <Stack.Screen name="Home" component={Home} />
          )}
        </Stack.Navigator>
      </NavigationContainer>
    </Auth.Provider>
  );
}

const styles = StyleSheet.create({
  container: {
    paddingTop: Constants.statusBarHeight + 20,
    padding: 20,
  },
  input: {
    marginBottom: 20,
  },
});

这是一个工作示例.

https://snack.expo.io/@raajnadar/react-navigation-auth-example

注意 - 这是一个非常基本的设置,您必须对身份验证设置进行验证和正确的令牌检查,您不能依赖只有 2 个选项 true 或 false 的三元操作,您可能还有一个中间状态,如身份验证检查.

Note - this is a very basic setup you must do the validation and proper token check for auth setup you cannot rely on a ternary operation that has only 2 options true or false, You might also have an intermediate state like auth checking.

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

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