React Native: Invariant Violation: The navigation prop is missing for this navigator

折月煮酒 提交于 2020-01-21 09:41:47

问题


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 />;
  }
}


来源:https://stackoverflow.com/questions/53602798/react-native-invariant-violation-the-navigation-prop-is-missing-for-this-navig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!