TabNavigator / redux with dynamic route configs

江枫思渺然 提交于 2019-12-24 22:33:20

问题


I'm developing a react-native app with a bottom-tab-navigator, and would like navigation options to depend on the screen being displayed, something like:

AppNavigator.js:

class AppNavigator extends React.Component{
    isRouteEnabled = (routeName) => {
        return this.props.route == routeName;
    }

    render() {
        const tabNavigator = createBottomTabNavigator({
            Home: HomeScreen,
            Screen2: Screen2,
            // tab to be conditionally displayed
            ...(this.isRouteEnabled('Screen3') ? { Screen3 : Screen3} : {})
        });

        const AppNavigator = createAppContainer(tabNavigator);
        return <AppNavigator />
    }
}

The problem I'm having is accessing this.props within this class, currently it's always undefined. If possible I'd like it to use values from my redux store, however if I wrap AppNavigator in a connect() call making it a higher-level component navigation no longer works at all (for reasons I don't understand):

const mapStateToProps = (state) => ({ route: state.route })
export default connect(mapStateToProps)(AppNavigator);

App.js is straightforward:

export default class App extends React.Component {
    render() {
        return (
            <Provider store={appStore}>
                <AppNavigator />
            </Provider>
        );
    }
}

Am I missing something - is it possible to have a navigator with dynamic behavior that depends on values stored in redux?


回答1:


Current version of React Navigation has a static configuration API, which means all configuration must be done outside render. This makes use cases such as dynamic navigators impossible until React Navigation 4.

React Navigation 5 has a new component-based API to configure navigators, which makes dynamic navigators possible:

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

const Tab = createBottomTabNavigator();

function AppNavigator() {
  const isRouteEnabled = (routeName) => {
    return this.props.route == routeName;
  }

  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={HomeScreen} />
      <Tab.Screen name="Screen2" component={Screen2} />
      {isRouteEnabled('Screen3') && (
        <Tab.Screen name="Screen3" component={Screen3} />
      )}
    </Tab.Navigator>
  );
}

const mapStateToProps = (state) => ({ route: state.route });

export default connect(mapStateToProps)(AppNavigator);

Documentation: https://reactnavigation.org/next

Keep in mind that React Navigation 5 is still in alpha.



来源:https://stackoverflow.com/questions/58051853/tabnavigator-redux-with-dynamic-route-configs

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