Redux thunk不会使用异步功能的响应进行更新

时间:2018-10-27 20:39:57

标签: reactjs redux geolocation react-redux redux-thunk

我一直在遵循设置redux-thunk的指南,因此我可以获取用户的地理位置,然后调度和更新状态。但是,每次我尝试使用响应数据分派操作时,它只会将数据设置为null。

当我尝试模拟带有超时的API调用并设置一些随机值时,它可以正常工作。

geoLocationActions.js

export function geoLocationActions() {
   return dispatch => {
    const geolocation = navigator.geolocation;
    geolocation.getCurrentPosition((position) => {
        console.log(position.coords);
        dispatch({
            type: 'FETCH_USER_LOCATION_SUCCESS',
            payload: position
        });
    });
  } 
};

MapContainer.js

import React from "react";
import { geoLocationActions } from '../../../actions/geoLocationActions';
import { connect } from 'react-redux';

class MapContainer extends React.Component {

    componentWillMount() {
        this.props.geoLocationActions();
    }

    render() {
        return (
            <div>
                <p>Fetching location...</p>
            </div>
        );
    }
}

// update current geolocation state
const mapDispatchToProps = (dispatch) => {
    return {
        geoLocationActions: () => dispatch(geoLocationActions())
    };
}

const mapStateToProps = (state) => {
    return {
        state: state
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(MapContainer);

reducers.js

case 'FETCH_USER_LOCATION_SUCCESS':
        return {
            ...state,
            userLocation: action.payload
        }

store.js

import { createStore, combineReducers, applyMiddleware, compose } from 

'redux';
import reducer from '../reducers/reducers';
import reduxThunk from "redux-thunk";

const rootReducer = combineReducers({
    state: reducer
});

export const store = createStore(
    rootReducer,
    compose(
        applyMiddleware(reduxThunk),
        window.devToolsExtension ? window.devToolsExtension() : f => f
    )
);

1 个答案:

答案 0 :(得分:2)

它将变成一个HTML5地理位置对象。您需要将其转换为可以使用JSON.stringify序列化的常规对象。 您可以使用此方法:

const geopositionToObject = geoposition => ({
  timestamp: geoposition.timestamp,
  coords: {
    accuracy: geoposition.coords.accuracy,
    latitude: geoposition.coords.latitude,
    longitude: geoposition.coords.longitude
  }
})

像这样更新您的geoLocationActions.js:

export function geoLocationActions() {
   return dispatch => {
    const geolocation = navigator.geolocation;
    geolocation.getCurrentPosition((position) => {
        const positionObj = geopositionToObject(position)
        console.log(positionObj);
        dispatch({
            type: 'FETCH_USER_LOCATION_SUCCESS',
            payload: positionObj
        });
    });
  } 
};

您可以查看my repo来查看相同的代码。