React native - 防止用户返回登录屏幕

React native - prevent user from going back to login screen

我使用 Facebook SDK 创建了一个登录按钮。用户登录后,应用程序将导航到第二个屏幕 (NavigatorIOS)。从第二个屏幕,用户可以使用导航(后退按钮)返回登录屏幕。

如果用户已经登录,如何防止他返回登录屏幕?

index.ios.js

import React, { Component } from 'react'

import {
  AppRegistry,
  StyleSheet,
  NavigatorIOS
} from 'react-native'

import LoginView from './src/login-view'

class MyApp extends Component {
  render() {
    return (
      <Provider store={store}>
        <NavigatorIOS
          initialRoute={{
            component: LoginView,
            title: 'MyApp',
            index: 0
          }}
        />
      </Provider>
    );
  }
}
AppRegistry.registerComponent('MyApp', () => MyApp);

登录视图

import React, {Component} from 'react'
import {
    View,
    Text,
    StyleSheet,
    TouchableHighlight,
} from 'react-native'

import CategoryView from './category-view'

import {LoginButton, AccessToken, GraphRequest, GraphRequestManager} from 'react-native-fbsdk'

class LoginView extends Component {
    goToCategoryView = () =>
        this.props.navigator.push({
            title: 'Categories',
            component: CategoryView,
        })

    render(){
        return(
            <View style={styles.container}>
                <LoginButton
                    readPermissions={['public_profile','email']}
                    onLoginFinished={
                        (error, result) => {
                            if (error) {
                                console.log('login has error: ', result.error)
                            } else if (result.isCancelled) {
                                console.log('login is cancelled.')
                            } else {
                                AccessToken.getCurrentAccessToken().then((data) => {    
                                    this.goToCategoryView()
                                })
                            }
                        }
                    }
                    onLogoutFinished={() => {console.log('logged out')}} />
            </View>
        )
    }
}

export default LoginView

先 pop() 关闭登录屏幕,然后 push() 打开新屏幕,或者尝试 replace() 怎么样? [https://facebook.github.io/react-native/docs/navigator.html]

还有一件事,您应该在登录屏幕上检查用户是否已登录,并显示注销而不是登录。 (如果你使用redux来存储用户令牌,你可以检查令牌是否存在并且仍然有效)

使用 Navigator,您可以使用 resetTo(startingRoute) 方法重置堆栈并从您过去的路线开始一个新的堆栈作为参数。这样做会阻止在堆栈中返回导航。

如果我没有误解你的组件,你应该使用这样的东西:

goToCategoryView = () => {
    //Replace here push with resetTo
    this.props.navigator.resetTo({
        title: 'Categories',
        component: CategoryView,
    })
}

Facebook Docs

就像你说的"One last question on the topic - once user is logged in, if I refresh the simulator, it goes back to Login screen showing Facebook continue button. Is it possible to also prevent going back to that screen on refresh/reload?"

如果您使用基于令牌的身份验证,则通过 AsyncStorage.setItem("jwtToken", token)[将用户令牌存储在 AsyncStorage 中=18=] 然后使用 AsyncStorage.getItem('jwtToken') 检查它是否存在令牌将用户重定向到主屏幕否则登录屏幕

// Fetch the token from storage then navigate to our appropriate place
const userToken = await AsyncStorage.getItem('jwtToken');


//set auth token header auth 
setAuthToken(userToken);
// // decode token and get user and experire
const decoded = jwt_decode(userToken);

// set user and isAuthenticated
// this will help you to login as current user
store.dispatch(setCurrentUser(decoded)); 

// This will switch to the App screen or Auth screen and this loading
//check if token is there or not

if (userToken === null) {

  //else logout to login page
  Actions.login()
  console.log(userToken)


} else {

  //if token then redirect to main screen
Actions.main()
console.log(userToken)

}
navigation.reset({
  index: 0,
  routes: [{ name: 'SCREEN_NAME' }],
});

这是截至 2020 年 8 月 28 日,反应导航 5,

您可以在此处阅读更多相关信息 => https://reactnavigation.org/docs/navigation-prop/#reset