【问题标题】:Redux: Is there any smart way to avoid the antipattern of importing store for helper files?Redux:有什么聪明的方法可以避免为帮助文件导入商店的反模式吗?
【发布时间】:2018-09-24 12:31:47
【问题描述】:

我目前正在使用 Redux、状态管理和 Firebase Cloud Messaging 构建一个 React Native 应用程序以进行实时通信。

在 Android you are required 的后台使用 FCM 创建名为 bgMessaging.js 的文件。

// @flow
import firebase from 'react-native-firebase';
// Optional flow type
import type { RemoteMessage } from 'react-native-firebase';

export default async (message: RemoteMessage) => {
    // handle your message

    return Promise.resolve();
}

我的问题是我需要在这里发送一个动作。我为此找到的唯一解决方案是导入我的商店并致电store.dispatch()。有人告诉我这是一种反模式,被认为是不好的做法。除了反模式,我还能做什么?

编辑: 马克·埃里克森本人非常友善,gave his opinion on this topic。谢谢马克!

【问题讨论】:

  • React 组件之外的 redux 使用示例很少,因为它们通常是高级用例(如您自己的)。我认为这将是反应组件中的反模式,而不是纯 JS 代码之外的反模式。你有关于这是一种不好的做法的消息来源吗?
  • afaik 反模式正在使 redux 存储成为单例,这主要是因为它使编写测试变得更加复杂,因为很难为特定测试隔离存储实例。

标签: react-native redux react-redux firebase-cloud-messaging react-android


【解决方案1】:

我在编写应用程序时也遇到了同样的情况。我的 React Native 应用程序的方法是创建 React 组件,但在 React 组件之外处理我的大量数据获取/处理 - 因为我不知道我是否会一直使用 React,但想为我的其他 Type/JavaScript 项目创建可重用的模块。例如,我创建了一些处理各种 API 的帮助文件,但是当我将 Redux 集成到我的项目中时 - 我遇到了同样的问题。我如何在不重新添加到您的商店的情况下发货(我可以看到这可以被视为反模式)。

阅读几篇文章,没有任何地方可以表明这种方法是“反模式”。很多时候,商店是在 React 上下文中导入的(这不需要)——这就是反模式。在您的用例中,我真的不明白这怎么可能是反模式,当我做同样的事情时,我当然得出了这个结论。在我看来,应用程序的“通用”部分应该被应用程序的许多其他部分使用。

【讨论】:

    【解决方案2】:

    我看到的是,您需要提供一个具有单个 arg 的函数,类型为 RemoteMessage,它返回一个承诺,并且您需要将该函数提供给 registerHeadlessTask(对于某些人来说,包装在另一个函数中)原因..)

    如果你的 bgMessaging 文件看起来像这样会怎样..

    // @flow
    import firebase from 'react-native-firebase';
    // Optional flow type
    import type { RemoteMessage } from 'react-native-firebase';
    
    export default store => {
      return async (message: RemoteMessage) => {
        // handle your message
        store.dispatch();
        return Promise.resolve();
      }
    }
    

    在你的索引中你做到了..

    import bgMessaging from './src/bgMessaging';
    
    const store = redux.createStore();
    
    const bgMessagingFn = bgMessaging(store);
    
    // Current main application
    AppRegistry.registerComponent('ReactNativeFirebaseDemo', () => bootstrap);
    // New task registration
    AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => bgMessagingFn);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 2021-02-25
      • 2021-05-25
      • 1970-01-01
      • 2014-04-01
      • 2012-04-16
      • 2017-04-16
      相关资源
      最近更新 更多