如何在routeConfig中访问Redux存储(反应导航)

时间:2019-11-28 13:51:25

标签: react-native redux react-navigation

这是代码示例:

const mapStateToProps = (state: RootState) => ({
  isSwipeEnabled: state.permissions.isSwipeEnabled,
});

const MainNavigator = createMaterialTopTabNavigator(
  {
    Screen1,
    Screen2: {
      screen: Screen2,
      navigationOptions: {
        swipeEnabled: isSwipeEnabled, <==HERE I WANT TO USE MY REDUX STATE
      },
    },
  },
  {
    initialRouteName: 'Screen1',
    tabBarPosition: 'bottom',
  },
);

export default connect(mapStateToProps)(MainNavigator);

是否可以在createMaterialTopTabNavigator函数中访问redux? 如果是,怎么办?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以在连接到redux的App组件的构造函数中创建导航器。在构造函数中,您可以从props访问映射状态:

const mapStateToProps = (state: RootState) => ({
    isSwipeEnabled: state.permissions.isSwipeEnabled
});

class NavigationApp extends React.Component {
    constructor(props) {
        super(props);

        this.mainNavigator = createMaterialTopTabNavigator(
            {
                Screen1,
                Screen2: {
                    screen: Screen2,
                    navigationOptions: {
                        // here you now can use your mapped redux state from props
                        swipeEnabled: props.isSwipeEnabled, 
                    }
                }
            },
            {
                initialRouteName: 'Screen1',
                tabBarPosition: 'bottom'
            },
        );
    }

    render() {
        // use here any function from react-navigation which you are using in your environment
        // e.g. createAppContainer
        // in this example I am using createBrowserApp for using react-navigation in web app
        const App = createBrowserApp(this.mainNavigator);
        return (<App />);
    }
}

export default connect(mapStateToProps)(NavigationApp);