Dynamic navigation items in Drawer Navigator

2020-04-11 11:20发布

问题:

I want to populate DrawerNavigator from response from an api. How can the drawer items be loaded dynamically?

Eg

    'someName1': { screen: (props) => <someView {...props} viewId='someId2' /> },
    'someName2': { screen: (props) => <someView {...props} viewId='someId2' /> },

回答1:

This is how I solved it-

In render method-

const Nav = DrawerNavigator(this.getNavItems(this.state.drawerSource.navItems));

        const AppNavigator = (StackNavigator(
            {
                Drawer: { screen: Nav },
            },
            {
                initialRouteName: "Drawer",
                headerMode: "none",
            })
        );

        return (<AppNavigator />);

getNavItems(navItems) {
    return navItems.reduce((routes, navItem) => {
        routes[navItem.id] = this.getNavItem(navItem);

        return routes;
    }, {});
}

getNavItem(navItem) {
    return {
        screen: (props) => <MyScreen {...props} id={navItem.id} />,
        navigationOptions: {
            ***any navigation properties
        }
    }        
}


回答2:

Instead of providing Screens directly to drawerComponent, provide a custom component for your drawermenu using the contentComponent as options to your DrawerNavigator. Then you can style and edit the drawerMenu anyway you want it. In that component, you can make an API call, get the list of menu items and load them in the component render method, which will be shown as the drawerMenu.

Note : You should make sure that you do not call this API very often, because if you do, for a while, user may get a blank drawerMenu until the API response is received. One way to handle this is to save the menu in Redux store and make the API call on the starting of the app, and have it stored/persisted in redux store.

I hope you found this answer helpful.