this.props.navigation.navigate无法导航到其他屏幕

时间:2018-10-14 20:58:25

标签: react-native react-navigation

我有一个标签导航器和堆栈导航器。这是结构;

const MainNavigator = createBottomTabNavigator({
      welcome: { screen: WelcomeScreen },
      auth: {
        screen: createStackNavigator({
          auth: {
            screen: AuthScreen,
            navigationOptions: {
              header: null
            }
          },
          login: {
            screen: LoginScreen,
            navigationOptions: {
              title: 'Login',
              headerTintColor: '#fff',
              headerStyle: {
                backgroundColor: '#3f2141'
              }
            }
          },
          newAccount: {
            screen: NewAccountScreen,
            navigationOptions: {
              title: 'Create an Account',
              headerTintColor: '#fff',
              headerStyle: {
                backgroundColor: '#3f2141'
              },
              headerTitleStyle: {
                fontSize: 20
              }
            }
          }
        }),
      },
      main: { screen: MainScreen }
    })

尝试从身份验证屏幕转到登录屏幕或新帐户屏幕时没有问题。但是,如果成功创建帐户,我会尝试从新帐户屏幕转到主屏幕。这是尝试执行此操作的操作代码;

export const createUser = ({ email, password }) => {
  return(dispatch) => {
    dispatch({ type: CREATE_USER });

    firebase.auth().createUserWithEmailAndPassword(email, password)
      .then(user => createUserSuccess(dispatch, user))
      .catch(() => createUserFail(dispatch));
  };
};

const createUserFail = (dispatch) => {
  dispatch({ type: CREATE_USER_FAIL })
};

const createUserSuccess = (dispatch, user) => {
  dispatch({
    type: CREATE_USER_SUCCESS,
    payload: user
  });
  navigateToMainScreen();
};

const navigateToMainScreen = () => {
  this.props.navigation.navigate('main')
};

但是导航功能在这里不起作用,因此用户创建了帐户,但屏幕没有变化。我知道了,这可能是一个新的帐户屏幕出现在堆栈导航器中,而主屏幕出现在选项卡导航器中的原因,但是我无法解决问题。

1 个答案:

答案 0 :(得分:1)

如果您尝试在单独的组件中调用this.props.navigation.navigate,则必须先将navigation道具传递给它。假设您要在navigation中使用NewAccountScreen,然后像这样传递道具:

<NewAccountScreen navigation={this.props.navigation}/>

需要渲染NewAccountScreen的父组件中。

在应用程序中任何地方使用navigation的另一种方法是使用withNavigation。遵循official documentation

import React from 'react';
import { Button } from 'react-native';
import { withNavigation } from 'react-navigation';

class NewAccountScreen extends React.Component {
  // your code including the call to this.props.navigation.navigate()
  // ...
}

// withNavigation returns a component that wraps NewAccountScreen
// and passes in the navigation prop:

export default withNavigation(NewAccountScreen);
  

使用这种方法,您可以在应用程序中的任何位置呈现NewAccountScreen   无需明确传递导航道具,它将作为   预期的。

另一方面,我强烈建议您重新考虑您的路由器结构。您可能有理由,但是将auth和主屏幕放在同一createBottomTabNavigator中对我来说意义不大。关于official documentation的使用createSwitchNavigator的认证流程,这将使您的生活更轻松。考虑在项目变得更加复杂之前试一试!