Dynamic route with React Navigation

╄→гoц情女王★ 提交于 2019-12-07 18:44:48

问题


I have a react native app running with react navigation 3.9 with 2 components Signup and Event:

export default class Signup extends React.Component {
}


export default class Event extends React.Component {
}

Also there is a splash component which retrieve local token.

Whenever there is a token retrieved from local drive, then the initial route is Event. Otherwise the it is Signup.

const stack = createStackNavigator ({
   Event: Event,
   Signup: Signup,
},{
  InitialRouteName: InitRoute  //<<either Event or Signup
})

const initScreen = createSwitchNavigator({
  Splash: Splash,
  App: stack,
})

export default createAppContainer(initScreen)

Here InitRoute needs to be set by checking local token which is retrieved in splash component. Dynamic routes is not very straight forward with react navigation. What is a good way to implement it with react navigation?


回答1:


You can create dynamic routes based on the token. You'll need a screen that renders those two routes. Like

// app renders createStackNavigator with Event and Signup
const routes = {
  Event: {
    screen: Event,
    navigationOptions: {
      title: 'Event',
    },
  },
  Signup: {
    screen: Signup,
    navigationOptions: {
      title: 'Signup',
    },
  },
};

class App extends React.Component {

  // creates dynamic routes
  createDynamicRoutes = initiaRoute => {
    return createAppContainer(
      createStackNavigator(routes, {
        initialRouteName: initiaRoute,
      })
    );
  };

  render() {
    // get initial route from splash screen
    // this.props.navigation.navigate('App', { init: 'init screen' });
    const initiaRoute = this.props.navigation.state.params.init || 'Event';

    // create routes and set initial route
    const AppContainer = this.createDynamicRoutes(initiaRoute);
    return <AppContainer />;
  }
}

InitScreen navigator renders App and Splash

const InitScreen = createSwitchNavigator({
  Splash: Splash,
  App: App,
})

export default createAppContainer(InitScreen);

Demo



来源:https://stackoverflow.com/questions/56392339/dynamic-route-with-react-navigation

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