React-Navigation v3の変更点


React-navigationで今までできていたものがエラーで返ってきてしまった、、、

React-Navigatorを利用してみる(基礎編)
ーStack Navigatorの実装のところでハマりました。

エラー内容

Invariant Violation: The navigation prop is missing for this navigator. In react-navigation 3 youmust set up your app container directly. More info: https://reactnavigation.org/docs/en/app-containers.html

エラー内容でググってみると、同じような人が!!
https://stackoverflow.com/questions/53367195/invariant-violation-the-navigation-prop-is-missing-for-this-navigator

そして、React-Navigation.org にも記載がありました。

Note: In v2 and earlier, the containers in React Navigation are automatically provided by the create*Navigator functions. As of v3, you are required to use the container directly. In v3 we also renamed createNavigationContainer to createAppContainer.

どうやら、v2ではcreate*Navigator関数を書くことで、勝手にコンテナの中に入れてくれていたみたい。
v3は自分でコンテナに入れる必要があるとのこと。

修正前コード

App.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { createStackNavigator, createBottomTabNavigator, createDrawerNavigator } from 'react-navigation';

//import creens
import Single1 from './screens/Single1';
import Single2 from './screens/Single2';
import Stack1 from './screens/Stack1';
import Stack2 from './screens/Stack2';
import Tab1 from './screens/Tab1';
import Tab2 from './screens/Tab2';

//stack
const Stack = createStackNavigator(
  {
    Stack1: { screen: Stack1 },
    Stack2: { screen: Stack2 },
  },
  {
    initialRouteName: 'Stack1'
  }
);

export default class App extends React.Component {
  render() {
    return (
      <Stack />
    );
  }
}

修正後コード

App.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
+ import { createStackNavigator, createBottomTabNavigator, createDrawerNavigator,createAppContainer } from 'react-navigation';

//import creens
import Single1 from './screens/Single1';
import Single2 from './screens/Single2';
import Stack1 from './screens/Stack1';
import Stack2 from './screens/Stack2';
import Tab1 from './screens/Tab1';
import Tab2 from './screens/Tab2';


const Stack = createStackNavigator(
  {
    Stack1: { screen: Stack1 },
    Stack2: { screen: Stack2 },
  },
  {
    initialRouteName: 'Stack1'
  }
);

+ const AppContainer = createAppContainer(Stack);


export default class App extends React.Component {
  render() {
    return (
+      <AppContainer 
+      ref={nav => {
+        this.navigator = nav;
+      }}
+      />
    );
  }
}

無事表示されました。