我使用create-react-native-app创建了一个简单的应用程序,并尝试在其中实现react-navigation。
该应用程序的结构非常简单。一开始,该应用程序将加载欢迎屏幕,如果已登录,用户可以决定注册或登录,然后用户将被直接定向到主屏幕。
浏览官方文档,我注意到不建议使用 Redux,如果没有,还有关于如何使用反应导航实现 redux 的参考。
有谁知道如何在没有 Redux 的情况下管理导航状态而不会生气?
解决方案:与导航一起使用
根据官方文档:
withNavigation 是一个高阶组件,它将导航道具传递到包装的组件中。当您无法将导航道具直接传递到组件中,或者不想在深度嵌套的子级的情况下传递它时,它很有用。
链接
因此,使用此组件可以访问任何组件的道具。
在 AuthLoadScreen 中检查用户令牌(在您的情况下为欢迎屏幕(。 并根据用户令牌发散到SignUp
屏幕或Home
。
例如。。。
- 包裹
WelcomeScreen(AuthLoading)
,Auth(SignUp, SignIn)
并Home( and others screen)
通过createStackNavigator
。
应用.js
import { createSwitchNavigator, createStackNavigator } from 'react-navigation';
// Implementation of HomeScreen, OtherScreen, SignInScreen, AuthLoadingScreen
// goes here.
const AppStack = createStackNavigator({ Home: HomeScreen, Other: OtherScreen });
const AuthStack = createStackNavigator({ SignIn: SignInScreen });
export default createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen,
App: AppStack,
Auth: AuthStack,
},
{
initialRouteName: 'AuthLoading',
}
);
- 在
AuthLoadingScreen
类constructor
写入检查用户令牌。
身份验证加载屏幕.js
import React from 'react';
import {
ActivityIndicator,
AsyncStorage,
StatusBar,
StyleSheet,
View,
} from 'react-native';
class AuthLoadingScreen extends React.Component {
constructor(props) {
super(props);
this._bootstrapAsync();
}
// Fetch the token from storage then navigate to our appropriate place
_bootstrapAsync = async () => {
const userToken = await AsyncStorage.getItem('userToken');
// This will switch to the App screen or Auth screen and this loading
// screen will be unmounted and thrown away.
this.props.navigation.navigate(userToken ? 'App' : 'Auth');
};
// Render any loading content that you like here
render() {
return (
<View style={styles.container}>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
}
重要的是如何在导航中将屏幕包装为堆栈,抽屉和点击。
您可以控制各种方式的堆栈
- 导航:转到另一个屏幕
this.props.navigation.navigate('yourscreen')
- 返回:关闭活动屏幕并向后移动
this.props.navigation.goBack()
特别是,当屏幕包含在堆栈中时,有更多的控制。
- popToTop:转到堆栈顶部
this.props.navigation.popToTop()
- 推:你会知道该怎么做。
- 流行:
- 替换:将当前路由替换为新路由
this.props.navigation.replace(yourscreen')
参考: https://reactnavigation.org/docs/en/auth-flow.html