reactjs - 如何在没有 Redux、React Native 的情况下管理 React-Navigation 的状态
问题描述
我使用 create-react-native-app 创建了一个简单的应用程序,并尝试在其中实现 react-navigation。
该应用程序的结构非常简单。一开始,应用程序将加载欢迎屏幕,用户可以在其中决定注册或登录,如果已经登录,那么用户将直接被引导到主主屏幕。
翻阅官方文档,我注意到不推荐使用 Redux,如果没有,也有一些关于如何通过反应导航实现 redux 的参考。
有谁知道如何在没有 Redux 的情况下管理导航状态而不生气?
解决方案:使用 withNavigation
根据官方文档:
withNavigation 是一个高阶组件,它将导航道具传递给一个包装的组件。当您无法将导航道具直接传递到组件中时,它很有用,或者在嵌套深度嵌套的孩子的情况下不想传递它。
因此,使用该组件可以访问任何组件的 props。
解决方案
检查 AuthLoadingScreen 中的用户令牌(在您的情况下为欢迎屏幕)。并分散到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',
}
);
constructor
在类中写入检查用户令牌AuthLoadingScreen
。
AuthLoadingScreen.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')
- goBack:关闭活动屏幕并返回
this.props.navigation.goBack()
特别是,当屏幕包含在堆栈中时,有更多的控制。
- popToTop:到栈顶
this.props.navigation.popToTop()
- push:你会知道该怎么做。
- 流行音乐:
- 替换:用新路由替换当前路由
this.props.navigation.replace(yourscreen')
推荐阅读
- html - 将两个 p 元素并排放置,宽度为 50%
- c# - 列表
要字符串的项目 - java - 如何让我的角度 Spring 的 UI 更改显示
- javascript - PayPal REST SDK:删除送货地址和付款授权,使其进入待处理状态
- docker - PyCharm 无法在本地 docker-machine 中使用解释器
- twitter-bootstrap - 为什么没有类限制宽度的div
- python - Scrapy:ImportError:没有名为 scrapy_proxies 的模块
- cloud - 寻找与 jira 集成进行外部通信的工具
- javascript - 无法启用表单元素
- c# - 来自 label.text 奇怪行为的字符串