我正在进行api通话,但我无法将其返回给我的动作创建者

时间:2018-05-24 23:43:59

标签: javascript reactjs react-native mobile react-redux

我有一个动作创建者,它调用我的apI(这是它自己的文件),api工作,动作创建者也可以。我能够从api调用我的响应console.log,我的问题是将它返回给我的动作创建者,在那里进行了api函数调用。谢谢。



**ACTION CREATOR**

import * as types from './actionTypes';
import FootballApi from '../api/footballApi';
import { loadLeag_Success } from '.';



//type
export const LOAD_LEAG_GAMES_SUCCESS = 'LEAGUE_GAMES_SUCCESS';

export function loadLeag_Game_Success(data){
    //console.log("before dis", data);
    return;
};


export function getLeaguesGames(idArr, date) { 
    return function(dispatch) {
        Promise.all(FootballApi.getLeaguesGamesAPI(idArr, date))
        .then(() => {
// .        I WANT TO RETURN IT HERE.
               console.log("returned")
               
            })
        //      .catch(error => {
        //         throw(error)
        //    })
    };
}






**API FILE**

export default class FootballApi {  
  static getAllLeags() {
    return fetch('https://apifootball.com/api/?APIkey=42f53c25607596901bc6726d6d83c3ebf7376068ff89181d25a1bba477149480&action=get_leagues').then(response => {
         return response.json();
      }).catch(error => {
        return error;
    });
  }

    static getLeaguesGamesAPI(idArr, date){
    
      return idArr.map((id)=>{
        return fetch(`https://apifootball.com/api/?APIkey=42f53c25607596901bc6726d6d83c3ebf7376068ff89181d25a1bba477149480&action=get_events&from=${date}&to=${date}&league_id=${id}`)
        .then(res =>{
          return res.json();
        })
          .then((game) => {
            if(!game.error){
              //console.log("game")
              return game;
          }
        })
      })
    }
};




3 个答案:

答案 0 :(得分:0)

尝试这样做:

行动创作者

import * as types from './actionTypes';
import FootballApi from '../api/footballApi';
import { loadLeag_Success } from '.';



const LOAD_LEAG_GAMES_SUCCESS = 'LEAGUE_GAMES_SUCCESS';



export const loadLeag_Game_Success = (data) => {
    console.log(data)// The data will be here
 };


export function getLeaguesGames(idArr, date) { 
    return function(dispatch) {
        Promise.all(FootballApi.getLeaguesGamesAPI(idArr, date))
        .then((data) => {

               dispatch(loadLeag_Game_Success(data));
            })
              .catch(error => {
                 throw(error)
            })
    }; }

答案 1 :(得分:0)

假设您已经拥有中间件(如thunk或saga)设置。你的Promise.All的解析函数不接受数据参数。

Promise.all(FootballApi.getLeaguesGamesAPI(idArr, date))
    .then((data) => {
        dispatch(loadLeag_Game_Success(data));
    });

答案 2 :(得分:0)

我想通了,我删除了 -

   .then((game) => {
        if(!game.error){
         //console.log("game")
      }
     })

并将其放入我的动作创建者中。一切都按照我需要的方式运作。感谢。