React Native 身份验证和 StackNavigator 不刷新页面

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

我有一个在模拟器上运行的 Android 应用程序。我能够“登录”,但不会被重定向到主屏幕,相反,我必须在模拟器上重新加载应用程序,然后我会自动登录。注销也是如此......我可以单击按钮注销,但只有当我关闭并重新打开应用程序时,我才真正注销,如果我不关闭并重新打开应用程序,则只会保留在同一页面上。

我有以下相关代码片段:

在 App.jsx 中:

import React, { useEffect } from 'react'
import { AsyncStorage } from 'react-native'
import moment from 'moment'
import { NavigationContainer } from '@react-navigation/native'
import { createNativeStackNavigator } from '@react-navigation/native-stack'
import Login from './modules/Login'
import Home from './modules/Home'
import Nav from './modules/Nav'
import Events from './modules/Events/Events'
import ConsentForm from './modules/ConsentForm'


export default function App() {
  const [expired, setExpired] = React.useState(true)
  const [consented, setConsented] = React.useState(false)

  const Stack = createNativeStackNavigator()

  const getData = async () => {
    return await AsyncStorage.getItem('@myapp:jwt'); 
  }

  useEffect(() => {
    getData().then((value) => {
      value = JSON.parse(value)
      if(value == null){
        setExpired(true)
      }else{
        const now = moment()
        setExpired(now.isAfter(moment(value?.expiry)))
        setConsented(value?.consented)
      }
    })
  })

  return (
    <NavigationContainer>
    <Stack.Navigator>
      {!expired ? (
         consented ? ( 
          <>
          <Stack.Screen name="Home" component={Home} />
          <Stack.Screen name="Nav" component={Nav} />
          <Stack.Screen name="Events" component={Events} />
      </>
        ): (
          <>
          <Stack.Screen name="ConsentForm" component={ConsentForm} />
          </>
        )
      ) : (
        <>
        <Stack.Screen name="Login" component={Login} />
        </>
      )}
    </Stack.Navigator>
  </NavigationContainer>
  )}

这是我的登录屏幕:

import React from 'react'
import { *, AsyncStorage} from 'react-native' // imported a bunch of stuff here
import jwt_decode from 'jwt-decode'
import { MY_API_URL } from './constants'

const Login = ({ navigation }) => {
  const [username, onChangeUsername] = React.useState(null)
  const [password, onChangePassword] = React.useState(null)

  const postLoginInformation = () => {
    fetch(`${MY_API_URL}/login/`, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: username,
        password: password,
      }),
    })
      .then(async (res) => {
        const response = await res.json()
        const jwt = JSON.parse(response).jwt
        const decoded_jwt = jwt_decode(jwt)
        await AsyncStorage.setItem(
          '@myapp:jwt',
          JSON.stringify(decoded_jwt),
        )
      }).catch((e) => console.log('login error', e, `${MY_API_URL}/login/`))
  }

  return (
    <SafeAreaView style={styles.container}>
<!-- more page items in between -->
        <TouchableOpacity
          onPress={() => postLoginInformation()}
        >
          <Image
            source={require('../images/login/login_button.png')}
          />
        </TouchableOpacity>

    </SafeAreaView>
  )
}

export default Login

我添加了一些控制台语句来查看我何时登录,但是,一旦 jwt 更改,应用程序就不会“重新加载” - 有什么方法可以让它做到这一点吗?抱歉,如果很明显,这是我的第一个 React Native 应用程序。

谢谢!如果您需要更多信息,请告诉我。

react-native authentication jwt expo react-navigation
1个回答
0
投票

我的建议是,当登录过程成功时,您手动重定向到登录屏幕。所以你可以这样做:

import { useNavigation } from '@react-navigation/native';

const navigation = useNavigation();

navigation.navigate('Login'); //Add this line where login is successful. 

您可以将完全相同的逻辑应用于注销过程,只要注销过程成功完成,就重定向到登录页面。

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