getCurrentPositionEpic
当我在下面的代码中注释掉时,该应用程序可以工作。但是,如果我不加注释,我会收到错误消息:
动作必须是普通对象。使用自定义中间件进行异步操作。
export const rootEpic = combineEpics(
fetchCategoriesEpic,
getCurrentLocationEpic,
getCurrentPositionEpic
)
const store = createStore(
rootReducer,
initialState,
composeWithDevTools(
applyMiddleware(createEpicMiddleware(rootEpic))
)
)
location.epic.js
const getCurrentPosition$ = getCurrentPositionObservable(
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
)
getCurrentPosition$.subscribe(
(position) => {
console.log(position)
const positionObject = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
//store.dispatch(updateRegion(positionObject))
//getCurrentLocation(positionObject)
},
(err) => {
console.log('Error: %s', err)
},
() => {
console.log('Completed')
})
export const getCurrentLocationEpic = action$ =>
action$.ofType(GET_CURRENT_LOCATION)
.mergeMap(() =>
Observable.fromPromise(Geocoder.geocodePosition(makeSelectLocation()))
.flatMap((response) => Observable.of(
getCurrentLocationFulfilled(response)
))
.catch(error => Observable.of(getCurrentLocationRejected(error)))
)
export const getCurrentPositionEpic = action$ =>
action$.ofType(GET_CURRENT_POSITION)
.mapTo(() => getCurrentPosition$
.flatMap((response) => Observable.of(
getCurrentPositionFulfilled(response)
))
.catch(error => Observable.of(getCurrentLocationRejected(error)))
)
下面的代码只是一个帮助器,用于将本机反应转换navigator.geolocation.getCurrentPosition
为可观察的,而不是接受回调的函数。
callBackToObservable.js
import { Observable } from 'rxjs'
export const getCurrentPositionObservable = Observable.bindCallback(
(options, cb) => {
if (typeof options === 'function') {
cb = options
options = null
}
navigator.geolocation.getCurrentPosition(cb, null, options)
})
什么可能导致错误?
尝试通过商店:
export const getCurrentPositionFulfilledEpic = (action$, store) =>
action$.ofType(GET_CURRENT_POSITION_FULFILLED)
.mergeMap(() =>{
console.log(store)***************** store is populated here
return Observable.fromPromise(Geocoder.geocodePosition({
lat: store.getState().get('searchForm').get('position').lat,***but not here
lng: store.getState().get('searchForm').get('position').lng
}))
.flatMap((response) => Observable.of(
getCurrentLocationFulfilled(response)
))
.catch(error => Observable.of(getCurrentLocationRejected(error)))
}
)
使用https://github.com/devfd/react-native-geocoder _Geocoder.geocodePosition