首页 文章

使用Axios处理Redux中的api调用

提问于
浏览
18

晚上好大家!

我是React和Redux的初学者,所以如果听起来完全愚蠢的话,请耐心等待 . 我正在尝试学习如何在Redux中执行一些API调用,但这并不是很好 . 当我控制记录来自动作创建者的请求时,promise值总是“未定义”,因此我不确定我是否正确执行此操作 .

我的目标是从有效负载对象内的数据中获取信息并将其显示在组件内 . 过去几天我一直试图让这个工作起来,我完全迷失了 .

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

任何帮助将不胜感激 .

这是控制台的输出 .

enter image description here

enter image description here

Action Creator

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
    };
}

Reducer

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;
  }

Component

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);

5 回答

  • 4

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

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

    在你的动作文件中将是这样的:

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

    解决此问题的最佳方法是添加redux中间件http://redux.js.org/docs/advanced/Middleware.html以处理所有api请求 .

    https://github.com/svrcekmichal/redux-axios-middleware是一个可以使用的即插即用中间件 .

  • 4

    你可以用thunk做到这一点 . https://github.com/gaearon/redux-thunk

    你可以在 then 中调度一个动作,它会在从axios调用中得到响应时更新状态 .

    export function someFunction() {
      return(dispatch) => {
          axios.get(URL)
            .then((response) => {dispatch(YourAction(response));})
            .catch((response) => {return Promise.reject(response);});
        };
    }
    
  • 25

    我照顾这个任务是这样的:

    import axios from 'axios';
    
    export const receiveTreeData = data => ({
      type: 'RECEIVE_TREE_DATA', data,
    })
    
    export const treeRequestFailed = (err) => ({
      type: 'TREE_DATA_REQUEST_FAILED', err,
    })
    
    export const fetchTreeData = () => {
      return dispatch => {
        axios.get(config.endpoint + 'tree')
          .then(res => dispatch(receiveTreeData(res.data)))
          .catch(err => dispatch(treeRequestFailed(err)))
      }
    }
    
  • 3

    我也认为最好的方法是使用redux-axios-middleware . 设置可能有点棘手,因为您的商店应以类似的方式配置:

    import { createStore, applyMiddleware } from 'redux';
    import axiosMiddleware from 'redux-axios-middleware';
    import axios from 'axios';
    import rootReducer from '../reducers';
    
    const configureStore = () => {   
      return createStore(
        rootReducer,
        applyMiddleware(axiosMiddleware(axios))
      );
    }
    
    const store = configureStore();
    

    而你的动作创建者现在看起来像这样:

    import './axios' // that's your axios.js file, not the library
    
    export const FETCH_FLIGHT = 'FETCH_FLIGHT';
    
    export const getAllFlights = () => {
      return {
        type: FETCH_FLIGHT,
        payload: {
          request: {
            method: 'post', // or get
            url:'http://localhost:3000/flug'
          }
        }
      }
    }
    

相关问题