我不知道为什么我无法获得此调度功能以到达console.log(3)和console.log(4),我试图将调度从成功函数内部移出,但同样无法正常工作。
export const getDistance = (storeLocation) => {
console.log('called1')
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0,
};
const success = (pos) => {
console.log('called2')
return dispatch => {
console.log('called3')
dispatch({ type: FETCHING_GEO_DATA })
axios
.get(
`${process.env.REACT_APP_GEO_BASE_URL}?waypoint.0=${pos.coords.latitude},${pos.coords.longitude}&waypoint.1=${storeLocation}&du=mi&key=${process.env.REACT_APP_GEO_KEY}`
)
.then((res) => {
console.log('called4')
dispatch({
type: FETCHING_GEO_DATA_SUCCESS,
payload: res.data.resourceSets[0].resources[0].travelDistance.toFixed(1)
})
})
.catch((err) => {
console.log('called4')
dispatch({
type: FETCHING_GEO_DATA_FAILURE,
payload: err
})
});
}
}
const error = (err) => {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
return window.navigator.geolocation ? navigator.geolocation.getCurrentPosition(success, error, options) : null
};
答案 0 :(得分:0)
您没有调用成功内部返回的内部函数。
尝试一下:
const success = (pos) => {
console.log('called2')
((dispatch) => {
console.log('called3')
dispatch({
type: FETCHING_GEO_DATA
})
axios
.get(
`${process.env.REACT_APP_GEO_BASE_URL}?waypoint.0=${pos.coords.latitude},${pos.coords.longitude}&waypoint.1=${storeLocation}&du=mi&key=${process.env.REACT_APP_GEO_KEY}`
)
.then((res) => {
console.log('called4')
dispatch({
type: FETCHING_GEO_DATA_SUCCESS,
payload: res.data.resourceSets[0].resources[0].travelDistance.toFixed(1)
})
})
.catch((err) => {
console.log('called4')
dispatch({
type: FETCHING_GEO_DATA_FAILURE,
payload: err
})
});
})()
}
如果要保留成功函数而不传递参数,则可以立即调用调度内部函数(IIEF)
type ORDER = 'WALK' | 'RUN'
function takeOrder(order: ORDER) {
console.log (order);
console.log (typeof order);
}
takeOrder('WALK'); // doesn't give ORDER
takeOrder('SLEEP'); // string