更新变量的状态

问题描述 投票:0回答:1

美好的一天!我遇到了导航问题。我有 2 个导航状态。

  1. 当用户未登录时
  2. 授权 一切都运转良好 当我们第一次下载应用程序时,变量 isSignedIn = false。他向我展示了正确的屏幕。但是,当我将其更改为 true 时,根据文档,导航状态应该更改并切换到另一个屏幕。如果我重新启动应用程序,就会发生这种情况,我知道我需要以某种方式更新,但我不知道如何正确执行。
import React, {useEffect, useState} from 'react';
import {createNativeStackNavigator} from '@react-navigation/native-stack';

import AuthMain from '../screens/Authentication/AuthMain';
import Walkthrough from '../screens/Walkthrough/Walkthrough';
import OTPVerivification from '../screens/Authentication/OTPVerivification';
import OTPRecoveryPassword from '../screens/Authentication/OTPRecoveryPassword';
import UserInformation from '../screens/UserInformation/UserInformation';
import Main from '../screens/Main/Main';

import {getData} from '../AsyncStorage/AsyncStorageGetData';

const Stack = createNativeStackNavigator();

const App = () => {
  const [isSignedIn, setIsSignedIn] = useState(false);


  useEffect(() => {
    const fetchData = async () => {
      const storedUserData = await getData('userData');
      const storedUserObject = JSON.parse(storedUserData);
      if (storedUserObject !== null) {
        setIsSignedIn(storedUserObject.isLogin);
        console.log(isSignedIn);
      }
    };

    fetchData();
  }, []); // Зависимость от isSignedIn

  return (
    <Stack.Navigator>
      {isSignedIn ? (
        <>
          <Stack.Screen
            name="Main"
            component={Main}
            options={{headerShown: false}}
          />
        </>
      ) : (
        <>
          <Stack.Screen
            name="Walkthrough"
            component={Walkthrough}
            options={{headerShown: false}}
          />
          <Stack.Screen
            name="AuthMain"
            component={AuthMain}
            options={{headerShown: false}}
          />
          <Stack.Screen
            name="OTPVerivification"
            component={OTPVerivification}
            options={{headerShown: false}}
          />
          <Stack.Screen
            name="OTPRecoveryPassword"
            component={OTPRecoveryPassword}
            options={{headerShown: false}}
          />
          <Stack.Screen
            name="UserInformation"
            component={UserInformation}
            options={{headerShown: false}}
          />
        </>
      )}
    </Stack.Navigator>
  );
};

export default App;

这意味着通过单击按钮我们可以更改变量,这样导航就应该改变

import {View, Text} from 'react-native';
import React from 'react';
import {useNavigation} from '@react-navigation/native';

import {CustomButton} from '../../components/CustomButton';
import {storeData, getData} from '../../AsyncStorage/AsyncStorageGetData';
import {COLORS, SIZES, images, FONTS, icons, user} from '../../../constants';

const Main = () => {
  async function Exit() {
    user.userData.isLogin = false;
    const userString = JSON.stringify(user.userData);
    await storeData('userData', userString);
  }

  return (
    <View style={{flex: 1, backgroundColor: COLORS.background1}}>
      <CustomButton text="Выход" onPress={Exit} />
    </View>
  );
};

export default Main;

我尝试按照该示例进行操作,但没有任何效果https://reactnavigation.org/docs/auth-flow/

javascript react-native react-native-navigation
1个回答
0
投票

看起来我已经弄清楚了,阅读了文档,这就是发生的事情并且它有效。需要使用 const AuthContext = createContext();

import React, {createContext, useContext, useState} from 'react';

export const AuthContext = createContext();

export const AuthProvider = ({children}) => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  const setLoginStatus = status => {
    setIsLoggedIn(status);
  };

  return (
    <AuthContext.Provider value={{isLoggedIn, setLoginStatus}}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  return useContext(AuthContext);
};

import React from 'react';
import Navigation from './src/navigation';
import {AuthProvider} from './src/navigation/AuthContext'; // Import AuthProvider

const App = () => {
  return (
    <AuthProvider>
      <Navigation />
    </AuthProvider>
  );
};

export default App;

import React, {useEffect, useState} from 'react';
import {View, Text} from 'react-native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {NavigationContainer} from '@react-navigation/native';

import AuthMain from '../screens/Authentication/AuthMain';
import Walkthrough from '../screens/Walkthrough/Walkthrough';
import OTPVerivification from '../screens/Authentication/OTPVerivification';
import OTPRecoveryPassword from '../screens/Authentication/OTPRecoveryPassword';
import UserInformation from '../screens/UserInformation/UserInformation';
import Main from '../screens/Main/Main';
import {useAuth} from './AuthContext';
import {FONTS} from '../../constants';

import {getData} from '../AsyncStorage/AsyncStorageGetData';

const Stack = createNativeStackNavigator();

const App = () => {
  const {setLoginStatus, isLoggedIn} = useAuth();
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const storedUserData = await getData('userData');
        const storedUserObject = JSON.parse(storedUserData);
        if (storedUserObject !== null) {
          setLoginStatus(storedUserObject.isLogin);
        }
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) {
    return (
      <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
        <Text style={FONTS.h1}>Загрузка...</Text>
      </View>
    );
  }

  return (
    <NavigationContainer>
      <Stack.Navigator>
        {isLoggedIn ? (
          <>
            <Stack.Screen
              name="Main"
              component={Main}
              options={{headerShown: false}}
            />
          </>
        ) : (
          <>
            <Stack.Screen
              name="Walkthrough"
              component={Walkthrough}
              options={{headerShown: false}}
            />
            <Stack.Screen
              name="AuthMain"
              component={AuthMain}
              options={{headerShown: false}}
            />
            <Stack.Screen
              name="OTPVerivification"
              component={OTPVerivification}
              options={{headerShown: false}}
            />
            <Stack.Screen
              name="OTPRecoveryPassword"
              component={OTPRecoveryPassword}
              options={{headerShown: false}}
            />
            <Stack.Screen
              name="UserInformation"
              component={UserInformation}
              options={{headerShown: false}}
            />
          </>
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

© www.soinside.com 2019 - 2024. All rights reserved.