如何从不知道Redux的服务发送动作?

dag*_*oin 9 javascript redux

假设我有一个不知道Redux的地理定位服务,我将其配置如下:

backgroundGeoLocation.configure(
  callback // will be called with an argument when the coordinates change
);
Run Code Online (Sandbox Code Playgroud)

什么是最简单的方法使服务回调调度Redux操作而不store从单独的模块导出并使用store.dispatch()(因为这将是一个单例)?

Dan*_*mov 14

如果要将某些值传递给JavaScript中的某段代码,则需要使用函数.
例如,

function createGeoLocationService(store) {
  let backgroundGeoLocation = new BackgroundGeoLocation()
  backgroundGeoLocation.configure(coordinates => {
    store.dispatch({ type: 'UPDATE_COORDINATES', coordinates })
  })
  return backgroundGeoLocation
}
Run Code Online (Sandbox Code Playgroud)

现在,无论您在何处创建商店,都要创建该服务:

let store = createStore(reducer)
let backgroundGeoLocation = createGeoLocationService(store)
Run Code Online (Sandbox Code Playgroud)

如果您需要在组件中访问它,您可以:

  1. 使它成为单身(是的,不是你想要的,但对于仅限客户的应用来说它是一个有效的选项)
  2. 通过道具明确地传递它(可以变得乏味,但它是最直接和明确的方式)
  3. 通过上下文隐式传递它(非常简单,但你将处理一个不稳定的API,它可能会发生变化,所以这是你的良心)