【发布时间】:2017-04-27 11:06:19
【问题描述】:
我正在制作一个天气应用程序,它通过对 freegeoip.com 进行 API 调用来检测您当前位置的坐标,然后将这些坐标用于对 openweathermap.org 进行 API 调用以获取您当前位置的天气。
我将如何使用 redux thunk 做到这一点?
这是我当前的动作创建者代码:
import axios from 'axios';
export const FETCH_CURRENT_CITY = 'FETCH_CURRENT_CITY';
const API_KEY = '95108d63b7f0cf597d80c6d17c8010e0';
const ROOT_URL = `http://api.openweathermap.org/data/2.5/weather?appid=${API_KEY}`;
export function fetchCurrentCityCoords() {
const request = axios.get('http://freegeoip.net/json/');
console.log('Request coords:', request);
return (dispatch) => {
request.then(({response}) => {
dispatch(fetchCurrentCityWeather(response));
});
};
}
export function fetchCurrentCityWeather(coords) {
const lat = coords.data.latitude;
const lon = coords.data.longitude;
const url = `${ROOT_URL}&lat=${lat}&lon=${lon}`;
const request = axios.get(url);
console.log('Request weather:', request);
return (dispatch) => {
request.then(({response}) => {
dispatch({
type: FETCH_CURRENT_CITY,
payload: response
})
});
};
}
控制台日志:
Request coords: Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
Uncaught (in promise) TypeError: Cannot read property 'latitude' of undefined
at fetchCurrentCityWeather (bundle.js:26131)
at bundle.js:26125
【问题讨论】:
标签: reactjs redux redux-thunk