带有 React Navigation 的动态路由 [英] Dynamic route with React Navigation
问题描述
我有一个使用 react navigation 3.9 运行的 react native 应用程序,其中包含 2 个组件 Signup
和 Event
:
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.
每当从本地驱动器中检索到令牌时,初始路由是 Event
.否则就是Signup
.
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)
这里InitRoute
需要通过检查在splash组件中检索到的本地token来设置.动态路线对于反应导航并不是很直接.使用反应导航实现它的好方法是什么?
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?
推荐答案
您可以根据令牌创建动态路由.您将需要一个呈现这两条路线的屏幕.喜欢
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 导航器呈现 App 和 Splash
InitScreen navigator renders App and Splash
const InitScreen = createSwitchNavigator({
Splash: Splash,
App: App,
})
export default createAppContainer(InitScreen);
这篇关于带有 React Navigation 的动态路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!