简体   繁体   中英

React Navigation accessing redux state

I'm wondering if there is a way to access redux states in App.js?

App.js 代码截图

It is possible to obtain redux data from within App.js. You can do this by using the store#getState method. The only problem by using this method is that App.js will not be updated whenever the redux store changes.

To obtain data from the redux state and also subscribe to changes automatically you will have to use the useSelector hook or wrap your component with a HOC.

Currently, you're initializing the bottomTabNavigator outside a React component. I suggest that you move this to a dedicated container named MainFlow . This container will be responsible for rendering the bottomTabNavigator . Load this container for the mainFlow route instead of the createBottomTabNavigator.

import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { useSelector } from 'redux';

// import your page containers

const Tab = createBottomTabNavigator();

export default function MainFlow() {
  // here you can use the `useSelector` hook to get the icon
  const tabBarIcon = useSelector(state => state.routing.tabBarIcon);

  return (
    <NavigationContainer>
      <Tab.Navigator
        screenOptions={() => ({
          tabBarIcon: ({focused}) => {
            // render icon
          }
        })}
      >
        <Tab.Screen name="homeScreen" component={HomePageContainer} />
        <Tab.Screen name="explore" component={ExplorePageContainer} />
        {/* rest of the tabs */}
      </Tab.Navigator>
    </NavigationContainer>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM