如何创建一个Action Creator,使用axios进行2次API调用并返回1个有效负载?

时间:2017-04-26 13:46:25

标签: reactjs redux

我正在创建一个天气应用程序,它使用freegeoip的API检测您的位置坐标,然后将这些坐标连接到openweather API,该API返回包含当前位置天气的数据集。

动作创作者代码:

import axios from 'axios';

export const FETCH_CITIES = 'FETCH_CITIES';
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 fetchCurrentCity() {
  const request = axios.get('http://freegeoip.net/json/')
    .then(response => {
      const lat = reponse.data.latitude;
      const lon = response.data.longitude;
      const url = `${ROOT_URL}&lat=${lat}&lon=${lon}`;

      axios.get(url);
    }) 

  console.log('Request 2:', request);

  return {
    type: FETCH_CURRENT_CITY,
    payload: request
  }
}

减速机代码:

import { FETCH_CURRENT_CITY } from '../actions/index';

const INITIAL_STATE = { location: {}, temp: null, weather: null };

export default function(state = INITIAL_STATE, action) {

  switch(action.type) {
    case FETCH_CURRENT_CITY:
    console.log('Received2:', action.payload.data);
    return { ... state, temp: action.payload.data.main.temp, weather: action.payload.data.weather[0].main };
  }
  return state;
}

控制台日志:

Request 2: Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}

Received2: undefined

以上代码似乎不起作用。我是Redux的新手,所以任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:0)

这是问题所在。在这个函数中,

export function fetchCurrentCity() {
  const request = axios.get('http://freegeoip.net/json/')
    .then(response => {
      const lat = reponse.data.latitude;
      const lon = response.data.longitude;
      const url = `${ROOT_URL}&lat=${lat}&lon=${lon}`;

      axios.get(url);
    }) 

  console.log('Request 2:', request);

  return {
    type: FETCH_CURRENT_CITY,
    payload: request
  }
}

您不应该只返回对象{ type: FETCH_CURRENT_CITY, payload: request }。他们应该派遣

该函数应具有如下结构:

    export function actionWeatherData(response) {
      // change 3: dispatch!
      return {
        type:...
        payload: ....
      }
    }

    export function fetchWeatherData(url) {
      ....
      const promise = axios.get(url);
      ....
      promise.then((response) => {
        // Change 2. weather data is ready, now dispatch the payload to store
        dispatch(actionWeatherData(response));
      }
    }

    export function fetchCurrentCity() {
      const request = axios.get('http://freegeoip.net/json/')
        .then(response => {
          const lat = reponse.data.latitude;
          const lon = response.data.longitude;
          const url = `${ROOT_URL}&lat=${lat}&lon=${lon}`;
          // Change 1. Fetch weather data
          fetchWeatherData(url);
          return response;
        }) 

      console.log('Request 2:', request);
    }