React Native: Invariant Violation: The navigation

2020-03-30 04:58发布

问题:

My code is as follows:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import {LoginNavigator} from './src/components/login/LoginNavigator'
import {MainNavigator} from './src/components/main/MainNavigator'
import FBSDK from 'react-native-fbsdk'
import {createSwitchNavigator} from 'react-navigation'

const { AccessToken } = FBSDK

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      accessToken: null
    }
  }

  componentDidMount() {
    AccessToken.getCurrentAccessToken()
    .then((data) => {
      this.setState({
        accessToken: data.accessToken
      })
    })
    .catch(error => {
      console.log(error)
    })
  }

  render() {
    const Navigator = makeRootNavigator(this.state.accessToken)
    return <Navigator />
  }
}

const makeRootNavigator = (isLoggedIn) => {
  return createSwitchNavigator(
    {
      LoginNavigator: {
        screen: LoginNavigator
      },
      MainNavigator: {
        screen: MainNavigator
      }
    },
    {
      initialRouteName: isLoggedIn ? "MainNavigator" : "LoginNavigator"
    }
  )
}

and I'm getting the error above. Since my Navigators depend on the variables created in construtor, I needed to do it via render(). Following react-native documentation on application containers didn't help.

回答1:

In react-navigation v3, you must wrap makeRootNavigator with createAppContainer. Change your code to :

render() {
   const Navigator = createAppContainer(makeRootNavigator(this.state.accessToken));
   return <Navigator />
}

and don't forget to import createAppContainer on top of the file

import {createSwitchNavigator, createAppContainer} from 'react-navigation'


回答2:

This is working solution for above problem

import { createStackNavigator } from 'react-navigation-stack'
import Login from './src/Login';
import Fruits from './src/Fruits';
import FruitZoom from './src/FruitZoom';
import {createAppContainer } from 'react-navigation';
import React from 'react';

const AppNavigator = createStackNavigator({
  Login: { screen:Login},
  Fruits: { screen: Fruits},
  FruitZoom: { screen: FruitZoom}
}, {
  initialRouteName: 'Login',
  headerMode: 'none'
});

const Apps = createAppContainer(AppNavigator);
export default class App extends React.Component {
  render() {
      return <Apps />;
  }
}