如何在Redux中处理navigator.geolocation.getCurrentPosition()的异步行为,并在Redux上存储用户的位置?

时间:2018-12-21 11:03:53

标签: javascript react-redux redux-thunk

如何在Redux中处理navigator.geolocation.getCurrentPosition()的异步行为并在Redux状态下存储用户的位置?

我最近开始使用Redux。我想在Redux状态下存储用户坐标,因此不必在应用程序的每个页面上都调用它。我正在使用redux-thunk,当我使用它处理从API提取数据的异步行为时,它工作正常。但是,当我要处理来自navigator.geolocation.getCurrentPosition方法的异步行为时,它无法按预期工作。

// Action file

export function getUserLocation() {
    return dispatch => {
        const geolocation = navigator.geolocation;
        geolocation.getCurrentPosition(position => {
            console.log('position.coords', position.coords); // Getting the expected object
            dispatch({
                type: GET_USER_LOCATION,
                payload: position
            });
        });
    };
}


// Reducer file

import { GET_USER_LOCATION } from '../constants/ActionTypes';

function userLocationReducer(state = {}, action) {
    switch (action.type) {
        case GET_USER_LOCATION:
            console.log('action.payload', action.payload); // Getting the expected object
            return { ...action.payload };
    }
    return state;
}

export default userLocationReducer;


// View file

componentDidMount() {
    this.props.getUserLocation(); // Calling as expected
}

render() {
    console.log(this.props.userLocation) // Always an empty object...
}

我希望在我的视图组件的render方法中调用this.props.userLocation不是一个空对象,但它始终为空。

我确信this.props.userLocation是通过mapStateToProps方法正确插入的(我尝试从操作文件中传递不带那些异步方法的随机对象,并在视图上获取它)。我猜我的问题是由于getCurrentPosition()的异步行为引起的,我无法弄清楚如何在获得用户位置之后而不是之前就如何调度它。 感谢您的帮助。

0 个答案:

没有答案