我已经使用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);
loginview
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
使用导航器,您可以使用 resetTo(startingRoute)
方法重置堆栈,并从您过去的路由作为参数中启动新的堆栈。这样做将阻止在堆栈中导航。
如果我不误解您的组件,则应使用类似的东西:
goToCategoryView = () => {
//Replace here push with resetTo
this.props.navigator.resetTo({
title: 'Categories',
component: CategoryView,
})
}
Facebook文档
就像您所说的"关于该主题的最后一个问题 - 用户登录后,如果我刷新模拟器,它将返回到登录屏幕显示Facebook继续按钮。防止在刷新/重新加载上返回该屏幕?"
如果您使用的是基于令牌的auth,则将用户令牌存储在 asyncstorage > asyncstorage.setItem(" jwttoken",token)然后使用.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)
}
pop()登录屏幕首先关闭,然后按()在新屏幕上或尝试替换()?[https://facebook.github.io/react-native/docs/navigator.html]
另外一件事,您应该在登录屏幕上进行检查,以查看用户是否已登录并显示登录而不是登录。(如果您使用Redux存储用户令牌,则可以检查令牌是否存在并且仍然有效)
navigation.reset({
index: 0,
routes: [{ name: 'SCREEN_NAME' }],
});
这是截至2020年8月28日,反应导航5,
您可以在此处阅读更多有关它的信息=&gt;https://reaectnavigation.org/docs/navigation-prop/#reset