问题
Right now I am facing a problem.. Before my application gets mounted, I am fetching categories from an API. Now I want to have a dynamic app which always contains the newest data.
I want to have the different categories always as a separated screen. The functions I need for every category screen is always the same. So, I have build myself a screen template.
However, I have to fetch the different categories from the API and then import my template screen as many times as I have fetched categories to create a screen for each category. Furthermore, I need to pass the category to the template screen to set up a correct screen for each category..
Is this possible and can you give me a hint on how to do this?
Kind regards and Thank You!
回答1:
I understand that you want your drawer navigation to be dynamic in relation to the data received from the API. In that case, you should only create and render the drawer navigation after the api call.
After fetching the categories, iterate through them and build your route config. You should be able to override the navigationOptions
and manually set some params (containing your specific category) for each screen.
let routeConfig = {};
categories.map(category => {
routeConfig[category.key] = {
screen: CategoryScreen, // your template screen, common to every item
navigationOptions: (props) => {
props.navigation.setParams({ category });
}
}
});
const DrawerNav = createDrawerNavigation(routeConfig, { /*options*/ });
Then you'll have to render the drawer navigation component manually
render() {
return (
<DrawerNav screenProps={{}} />
);
}
Finally, within CategoryScreen
or whatever your screen component is, you can access the category in a way similar to the clasic navigation case: this.props.navigation.state.params.category
.
Some notes:
- The
DrawerNav
constant is just an example. Most probably you're going to want to make it a class property or a normal variable defined outside of the class but populated within. category.key
is yet again an example, you should make sure to replace it with something unique for each category, such as a string representation of the category id.- If you want to have different screen components for each category, you can simply pass a different component to
screen
based on the category in the current.map()
iteration.
来源:https://stackoverflow.com/questions/53469918/react-navigation-drawer-dynamically-routes-and-navigation-items