【问题标题】:React Navigation accessing redux stateReact Navigation 访问 redux 状态
【发布时间】:2020-10-26 14:18:10
【问题描述】:

我想知道是否有办法在 App.js 中访问 redux 状态?

【问题讨论】:

  • 我打算设置一个底部导航图标,其中图像来自 redux 状态
  • 提问的时候不要放截图。为了调试,我们复制粘贴代码,如果您截屏,这将变得不可能。 stackoverflow.com/help/how-to-ask
  • 请编辑问题并复制粘贴代码。

标签: reactjs react-native react-redux react-navigation


【解决方案1】:

可以从 App.js 中获取 redux 数据。您可以使用store#getState 方法来执行此操作。使用此方法的唯一问题是 App.js 将不会在 redux 存储更改时更新。

要从 redux 状态获取数据并自动订阅更改,您必须使用 useSelector 挂钩或使用 HOC 包装您的组件。

目前,您正在 React 组件外部初始化 bottomTabNavigator。我建议您将其移至名为 MainFlow 的专用容器中。这个容器将负责渲染bottomTabNavigator。为 mainFlow 路由而不是 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>
  );
}

【讨论】:

猜你喜欢
  • 2020-06-17
  • 2017-08-28
  • 2016-01-02
  • 2018-05-02
  • 2018-01-05
  • 2018-02-19
  • 2018-05-28
  • 2017-04-02
  • 1970-01-01
相关资源
最近更新 更多