使用Axios处理Redux中的api调用 [英] Handling api calls in Redux with Axios

查看:284
本文介绍了使用Axios处理Redux中的api调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家晚上好!

我是React和Redux的初学者,所以如果这听起来很愚蠢,请多多包涵.我正在尝试学习如何在Redux中执行一些API调用,但进展并不顺利.当我控制台记录操作创建者的请求时,promise值始终为"undefined",因此我不确定自己是否正确执行了此操作.

I'm a total beginner in React and Redux so please bear with me if this sounds totally stupid. I'm trying to learn how I can perform some API calls in Redux and it's not going all to well. When I console log the request from the action creator the promise value is always "undefined" so I'm not sure if I'm doing this correctly.

我的目标是从有效负载对象内部的数据中获取信息,并将其显示在组件内部.在过去的几天里,我一直在努力使它发挥作用,但我完全迷失了.

My goal is to grab the information from the data inside the payload object and display them inside the component. I've been trying to get this to work for the past days and I'm totally lost.

我正在使用Axios和redux-promise来处理呼叫.

I'm using Axios for and redux-promise to handle the call.

任何帮助将不胜感激.

这是控制台的输出.

动作创建者

import axios from 'axios';
export const FETCH_FLIGHT = 'FETCH_FLIGHT';

export function getAllFlights() {

const request = axios.get('http://localhost:3000/flug');
console.log(request);
  return {
    type: FETCH_FLIGHT,
    payload: request
    };
}

减速器

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

export default function(state = [], action) {
  switch (action.type) {
    case FETCH_FLIGHT:
    console.log(action)
      return [ action.payload.data, ...state ]
    }
   return state;
  }

组件

import React from 'react';
import { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getAllFlights } from '../actions/index';
import Destinations from './Destinations';

class App extends Component {

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

constructor(props) {
 super(props);
  this.state = {
 };
}

render() {
  return (
    <div>
    </div>
    );
 }

function mapStateToProps(state) {
 return {
   dest: state.icelandair
  };
}

function mapDispatchToProps(dispatch) {
 return bindActionCreators({ selectFlight: getAllFlights }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(App);

推荐答案

axios是承诺,因此您需要使用then来获得结果.您应该在单独的文件中请求api,并在结果返回时调用操作.

axios is the promise so you need to use then to get your result. You should request your api in a separate file and call your action when the result comes back.

 //WebAPIUtil.js
axios.get('http://localhost:3000/flug')
  .then(function(result){ 
    YourAction.getAllFlights(result)
  });

您的操作文件中将如下所示:

In your action file will be like this :

export function getAllFlights(request) {
  console.log(request);
  return {
    type: FETCH_FLIGHT,
    payload: request
  };
}

这篇关于使用Axios处理Redux中的api调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆