如何在没有Redux,React Native的情况下管理React-Navigation的状态

时间:2018-09-16 19:57:30

标签: reactjs react-native redux react-navigation

我使用create-react-native-app创建了一个简单的应用,并尝试在其中实现反应导航。

该应用程序的结构非常简单。首先,该应用程序将加载欢迎屏幕,用户可以在其中决定是否注册或登录(如果已登录),然后将用户直接定向到主主屏幕。

浏览官方文档时,我发现不建议使用Redux,如果没有,也很少提及如何通过react导航实现redux。


有谁知道如何在没有Redux的情况下管理导航状态而不会发疯?

解决方案:与导航一起使用

根据官方文档:

  

withNavigation是一个更高阶的组件,它将导航道具传递到包装的Component中。当您无法将导航道具直接传递到组件中,或者如果孩子嵌套得太深,则不想传递它,这将很有用。

LINK

因此,使用此组件可以访问任何组件的道具。

1 个答案:

答案 0 :(得分:1)

在AuthLoadingScreen(在您的情况下为欢迎屏幕)中检查用户令牌。 并根据用户令牌转到SignUp屏幕或Home

例如...

  1. 通过WelcomeScreen(AuthLoading)包装Auth(SignUp, SignIn)Home( and others screen)createStackNavigator

App.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',
  }
);
  1. 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()的顶部
  • 推:您将知道该怎么办。
  • 流行音乐:
  • 替换:用新的this.props.navigation.replace(yourscreen')
  • 替换当前路径

参考:https://reactnavigation.org/docs/en/auth-flow.html

相关问题