【问题标题】:Import a created redux store to dispatch an action from a non connected component导入创建的 redux 存储以从非连接组件调度操作
【发布时间】:2018-09-04 14:27:31
【问题描述】:

我正在使用 react-native 和 redux。我也在使用反应导航,我有一个底部选项卡导航器,其中第二个 RouteConfig 导航选项为 tabBarOnPress 提供了一个功能。我想在这个回调中向 redux 发送一些操作。

import store from "./Store"    

const BottomTab = createBottomTabNavigator(
    {
        First: FirstScreen,
        Second: {
           screen: SecondScreen,
           navigationOptions: {
               tabBarOnPress: ({ navigation }: any) => {
                   store.dispatch(someAction())
                   navigation.navigate("SecondScreenModal");
               }
           }
        },
        Third: ThirdScreen
    },
    {
        navigationOptions: ({ navigation }) => ({
        //..
    }
);

由于我找不到连接底部选项卡导航器的方法,我想知道在这种情况下直接导入创建的 redux 存储是否是不好的做法(我作为道具传递给提供者的相同)。

import rootReducer from "./RootReducer";
import {createStore} from "redux";

store = createStore(rootReducer)     
export default store

【问题讨论】:

    标签: react-native redux react-navigation


    【解决方案1】:

    在您希望调度 redux 操作的屏幕内(在您的情况下为 SecondScreen),设置一个与您要执行的功能相等的导航参数。您可以为参数命名任何名称,但我通常根据我将如何使用它来命名。

    componentDidMount = () => {
      this.props.navigation.setParams({ tabBarOnPress: this.props.myReduxActionCreator })
    }
    

    然后在您的屏幕导航选项中,您可以执行类似的操作来访问该功能。确保它与上面的参数名称相同,所以在这个例子中,'tabBarOnPress'

    const BottomTab = createBottomTabNavigator(
      {
        First: FirstScreen,
        Second: {
          screen: SecondScreen,
          navigationOptions: {
    
            // Access the function inside navigation params here
            tabBarOnPress: ({navigation}) => navigation.getParam('tabBarOnPress', null)
          }
        },
        Third: ThirdScreen
      },
      {
        navigationOptions: ({navigation}) => ({})
      }
    )
    

    【讨论】:

    • 很好的答案来解决我关于反应导航的问题。但是,如果直接使用导出的商店而不是经典的提供者/连接方式是一种不好的做法,那并不能真正回答。您能否也准确指出这一点?
    • 实际上我的参数是未定义的,FirstScreen 和 ThirdScreen 是 StackNavigator 会是个问题吗?
    【解决方案2】:

    const BottomTab = createBottomTabNavigator() 这个完整的代码箱mapStateToProps 之后,mapDispatchToProps 箭头函数。

        export default connect(mapStateToProps, mapDispatchToProps)(BottomTab);
    

    我相信你想这样做。

    【讨论】:

    • createBottomTabNavigator() 是一个返回组件的函数,它接受两个参数 RouteConfig 和 NavigationOptions。您希望如何在 navigationOptions 中访问 this.props.dispatch: { tabBarOnPress: ({ navigation }: any) => { store.dispatch(someAction()) navigation.navigate("SecondScreenModal"); } } ?
    猜你喜欢
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 2020-01-06
    • 2017-04-12
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    相关资源
    最近更新 更多