【问题标题】:How to do recurrent events in react/react-native with redux?如何使用 redux 在 react/react-native 中执行经常性事件?
【发布时间】:2017-01-08 13:35:24
【问题描述】:

我正在做一个反应原生应用程序,在用户的某些动作上将开始跟踪 gps 位置,并在其他停止。

但是我遇到了一些障碍,没有找到执行这种基于时间的位置跟踪器的正确方法,因为这种模式看起来并不自然。 以下是我的想法:

  1. 使用redux-thunk 将其视为异步。
  2. 使用redux-observable 定时事件。
  3. 使用sagas
  4. 在我的component 中使用SetTimeout(这是最简单的解决方案,但我不想阻止我的用户四处导航,我不认为这是 UI 责任)

【问题讨论】:

    标签: reactjs react-native redux redux-thunk redux-observable


    【解决方案1】:

    所以我将把这个作为未来的参考,在我写这个问题的时候,我终于找到了一个简单的解决方案。

    import * as types from './types'
    var gpsGetInterval 
    export function startLocationTracking(time = 1000){
        return dispatch => {
                gpsGetInterval = setInterval(() =>{
                    navigator.geolocation.getCurrentPosition(
                    (position) => {
                        dispatch({
                            type: types.NEW_POSITION,
                            state: JSON.stringify(position)
                        })
                    })
                }, time) 
                dispatch({
                    type: types.START_RUN
                })
            }
    }
    
    export function stopLocationTracking(){
        clearInterval(gpsGetInterval)
        return {
            type: types.STOP_RUN
        }
    }
    

    所以我知道这可能无法扩展,您可能需要在redux-observablesagas 下使用epics。我在这 2 中遇到的困难:

    • 使用redux-observable 清除重复事件不清楚(或者看起来像是一种暂停它的解决方法)。
    • 使用sagas 似乎并不容易扩展或聚合。

    redux-observables 这是我得到的代码,如果有人对这种情况有好的想法,我很想听听:):

    export function inStartRun(action$){
      return action$.ofType(types.START_RUN)
        .switchMap(function () {
          Rx.Observable
            .interval(1000)
            .do(function () { console.log('tick...') })
            .share()
            .mapTo({ type: types.STOP_RUN})
        });
    }
    

    特别感谢 Jay Phelps 在我在 repo 中提出的问题 https://github.com/redux-observable/redux-observable/issues/168

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 2023-03-13
      • 2020-10-20
      相关资源
      最近更新 更多