首页 > 解决方案 > 如何在 routeConfig 中访问 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?如果是,怎么做?

谢谢!

标签: react-nativereduxreact-navigation

解决方案


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

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);

推荐阅读