【问题标题】:Redux-Saga effects.put callbackRedux-Saga effects.put 回调
【发布时间】:2022-01-15 22:15:53
【问题描述】:

我在 @react-native-community/geolocation 的帮助下在我的 React Native 应用程序中实现手表地理定位功能,并且我创建了一个负责启动 地理定位的初始化 saga 函数。观看位置。我想传递一个 redux saga 回调函数,它会更新我的 redux 状态,但它不会触发回调 onGeolocationGet 函数:

function* initialize(): SagaReturnType<any> {
  try {
    yield effects.call(geolocation.watchPosition, function* onGeolocationGet(data) {
      yield effects.put(UserActions.updateCurrentLocation({ ...data.coords }))
    })
  } catch (err) {
    console.error(err)
  }
}

提前感谢各位小伙伴!

【问题讨论】:

    标签: react-native redux redux-saga saga


    【解决方案1】:

    不是 redux 传奇专家,但我相信基于堆栈溢出的 this example,您不需要调用该函数,即不需要

    effects.call

        function* initialize(): SagaReturnType<any> {
      try {
        yield (geolocation.watchPosition, function* onGeolocationGet(data) {
          yield effects.put(UserActions.updateCurrentLocation({ ...data.coords })
        })
      } catch (err) {
        console.error(err)
      }
    }
    

    【讨论】:

    • 不,它不起作用。这实际上完全没有意义
    【解决方案2】:

    并非每个生成器都是 saga - 就像您的情况一样,saga 库不知道它应该处理您作为回调传递给 watchPosition 的生成器。

    对于重复调用的回调,您需要使用eventChannel 实用程序。它允许您发出放入自定义通道的数据。然后,您可以使用各种 take 效果在此频道上收听。

    import {eventChannel} from 'redux-saga'
    
    function createGeolocationChannel = () => eventChannel(emitter => {
      const watchId = geolocation.watchPosition(data => {
        emitter({ ...data.coords });
      });
      return () => geolocation.clearWatch(watchId)
    })
    
    function* initialize(): SagaReturnType<any> {
      try {
        const geoChannel = yield effects.call(createGeolocationChannel);
        yield effects.takeEvery(geoChannel, function*(coords) {
          yield effects.put(UserActions.updateCurrentLocation(coords));
        })
      } catch (err) {
        console.error(err)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-30
      • 1970-01-01
      • 2021-11-14
      • 2017-04-25
      • 2017-06-14
      • 2020-06-18
      • 2019-02-21
      • 2020-12-21
      • 2017-08-19
      相关资源
      最近更新 更多