Dynamic navigation items in Drawer Navigator

女生的网名这么多〃 提交于 2019-12-02 02:23:48

问题


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.



来源:https://stackoverflow.com/questions/48573487/dynamic-navigation-items-in-drawer-navigator

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