【问题标题】:Handling api calls in Redux with Axios使用 Axios 在 Redux 中处理 api 调用
【发布时间】:2016-07-21 22:16:53
【问题描述】:

大家晚上好!

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

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

我正在使用 Axios for 和 redux-promise 来处理调用。

任何帮助将不胜感激。

这是控制台的输出。

动作创建者

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

【问题讨论】:

  • 什么不适合你?您的代码看起来不错。 redux-promise 希望有效载荷是一个承诺,看起来这就是你提供的。

标签: javascript reactjs promise redux axios


【解决方案1】:

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

【讨论】:

  • 感谢您的帮助:)
  • 是的,请将此标记为答案。虽然我个人喜欢 redux-axios-middleware,但这确实是最好的答案,应该标记为一个以备不时之需!
  • 我不明白这是如何工作的。你从哪里拨打axios.get
  • @AlanSchapira 它使用import axios from 'axios'导入到您的文件中
  • 你是如何在操作中调用 webAPIUtil 的?
【解决方案2】:

你可以用 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);});
    };
}

【讨论】:

    【解决方案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'
          }
        }
      }
    }
    

    【讨论】:

    • 能否请您发布演示,我如何从连接方法触发方法 api
    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

      我是这样处理这个任务的:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-02
        • 2020-05-13
        • 1970-01-01
        • 2018-08-05
        • 2021-06-18
        • 1970-01-01
        相关资源
        最近更新 更多