Search code examples
reactjsreact-nativereact-navigationreact-navigation-stack

How can i use react-navigation in class method?


import * as React from 'react';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { Text, View } from 'react-native';


class LoadingScreen extends React.Component {
  dataCheck = () => {
    for (i = 0; i < 5; i++) { // data loading time in real code
      if (i == 4) {
        this.props.navigation.navigate('AppStack')
      }
    }
  }
  render() {
    return (
      <View>
        <Text>loading</Text>
        {this.dataCheck}
      </View>
    );
  }
}

class MainScreen extends React.Component {
  render() {
    return (
      <View>
        <Text>mainscreen</Text>
      </View>
    );
  }
}


const AppNavigator = createStackNavigator(
  {
    main: MainScreen
  },
  {
    initialRouteName: 'main'
  }
)

const LoadNavigator = createSwitchNavigator(
  {
    load: LoadingScreen,
    AppStack: AppNavigator
  },
  {
    initialRouteName: 'load'
  }
)

export default createAppContainer(LoadNavigator)

I am trying to show loading screen while loading data. So I wrote method 'dataCheck' in class 'LoadingScreen' which waits until data is loaded(for statement in code above) and navigates to 'AppStack'. But I think "this.props.navigation.navigate('AppStack')" doesn't work. How can I use react-navigation in class's method?


Solution

  • You need to just replace

     {this.dataCheck}
    

    With

    {this.dataCheck()}