首页 > 解决方案 > 如何在没有 Redux、React Native 的情况下管理 React-Navigation 的状态

问题描述

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

该应用程序的结构非常简单。一开始,应用程序将加载欢迎屏幕,用户可以在其中决定注册或登录,如果已经登录,那么用户将直接被引导到主主屏幕。

翻阅官方文档,我注意到不推荐使用 Redux,如果没有,也有一些关于如何通过反应导航实现 redux 的参考。


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

解决方案:使用 withNavigation

根据官方文档:

withNavigation 是一个高阶组件,它将导航道具传递给一个包装的组件。当您无法将导航道具直接传递到组件中时,它很有用,或者在嵌套深度嵌套的孩子的情况下不想传递它。

关联

因此,使用该组件可以访问任何组件的 props。

标签: reactjsreact-nativereduxreact-navigation

解决方案


检查 AuthLoadingScreen 中的用户令牌(在您的情况下为欢迎屏幕)。并分散到SignUp屏幕或Home取决于用户令牌。

例如...

  1. 包裹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',
  }
);
  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()
  • push:你会知道该怎么做。
  • 流行音乐:
  • 替换:用新路由替换当前路由this.props.navigation.replace(yourscreen')

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


推荐阅读