отреагировать на ошибку при входе в систему для навигации - PullRequest
0 голосов
/ 16 февраля 2020

У меня проблема с экраном входа в систему. Все работает довольно хорошо, но моя проблема в том, что после успешного входа в систему я получаю ошибку полезной нагрузки. Я использую компонент функции, а не компонент класса. И все мои экраны находятся за пределами маршрута. js.

Ошибка

Мой маршрут. js код выглядит следующим образом:

 import  React, {  useState } from 'react';
import 'react-native-gesture-handler';
import {AsyncStorage} from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
/// All components of screens
import HomeScreen from './src/Component/HomeScreen';
import DefaultScreen from './src/Component/DefaultScreen';
import Privacy from './src/Component/Privacy';
import Signup from './src/Component/Signup';
import ForgetPassword from './src/Component/ForgetPassword';
import Dashboard from './src/Component/Dashboard';
import SplashScreen from './src/Component/SplashScreen';
const AuthContext = React.createContext();

export default function Routes(){
const Stack = createStackNavigator();
const [state, dispatch] = React.useReducer(
  (prevState, action) => {
    switch (action.type) {
      case 'RESTORE_TOKEN':
        return {
          ...prevState,
          userToken: action.token,
          isLoading: false,
        };
      case 'SIGN_IN':
        return {
          ...prevState,
          isSignout: false,
          userToken: action.token,
        };
      case 'SIGN_OUT':
        return {
          ...prevState,
          isSignout: true,
          userToken: undefined,
        };
    }
  },
  {
    isLoading: true,
    isSignout: false,
    userToken: null,
  }
);

React.useEffect(() => {
  // Fetch the token from storage then navigate to our appropriate place
  const bootstrapAsync = async () => {
    let userToken;

    try {
      userToken = await AsyncStorage.getItem('@kiklee-user-id');
    } catch (e) {
      // Restoring token failed
    }

    // After restoring token, we may need to validate it in production apps

    // This will switch to the App screen or Auth screen and this loading
    // screen will be unmounted and thrown away.
    dispatch({ type: 'RESTORE_TOKEN', token: userToken });
  };

  bootstrapAsync();
}, []);

const authContext = React.useMemo(
  () => ({
    signIn: async data => {
      // In a production app, we need to send some data (usually username, password) to server and get a token
      // We will also need to handle errors if sign in failed
      // After getting token, we need to persist the token using `AsyncStorage`
      // In the example, we'll use a dummy token

      dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
    },
    signOut: () => dispatch({ type: 'SIGN_OUT' }),
    signUp: async data => {
      // In a production app, we need to send user data to server and get a token
      // We will also need to handle errors if sign up failed
      // After getting token, we need to persist the token using `AsyncStorage`
      // In the example, we'll use a dummy token

      dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
    },
  }),
  []
);

if (state.isLoading) {
  // We haven't finished checking for the token yet
  return <SplashScreen />;
}
  //alert(authContext);


    return(
      <AuthContext.Provider value={authContext}>
      <NavigationContainer>
      <Stack.Navigator>
     {state.userToken == null ? (
  <>
    <Stack.Screen name="Home" component={HomeScreen} options={{ headerShown:false, animationTypeForReplace: state.isSignout ? 'pop' : 'push', }} />
    <Stack.Screen name="Privacy" component={Privacy} options={{ headerShown:false }} />
    <Stack.Screen name="ForgetPassword" component={ForgetPassword} options={{  headerShown:false }} />
    <Stack.Screen name="SignUp" component={Signup} options={{  headerShown:false }} />
    <Stack.Screen name="SplashScreen" component={SplashScreen} options={{ headerShown:false }} />
    </>
) : (
  <>
    <Stack.Screen name='Dashboard' component={Dashboard} />
    <Stack.Screen name="SplashScreen" component={SplashScreen} options={{ headerShown:false }} />

  </>
)}

      </Stack.Navigator>
    </NavigationContainer>
    </AuthContext.Provider>
            );



}

Мой экран входа это HomeScreen. js 'HomeScreen' и после входа я перенаправляю пользователя на Dashboard. js 'Dashboard'

1 Ответ

0 голосов
/ 17 февраля 2020

Я думаю, что код await AsyncStorage.getItem('@kiklee-user-id') возвращает ноль, поэтому значение state.userToken всегда равно нулю, а ваш компонент <Stack.Navigator> не имеет никакого Dashboard маршрута

...