使用React导航的动态路线

时间:2019-05-31 09:28:20

标签: react-native react-navigation

我有一个运行React React 3.9的React Native应用,其中包含2个组件SignupEvent

export default class Signup extends React.Component {
}


export default class Event extends React.Component {
}

还有一个启动组件,可以检索本地令牌。

只要从本地驱动器检索到令牌,则初始路由为Event。否则为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)

此处InitRoute需要通过检查在启动组件中检索到的本地令牌来设置。动态路线在反应导航中不是很简单。用React导航实现它的好方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以基于令牌创建动态路由。您将需要一个渲染这两条路线的屏幕。喜欢

// 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导航器呈现App和Splash

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

export default createAppContainer(InitScreen);

Demo