Javascript 使用 Axios 处理 Redux 中的 api 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36367648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:58:07  来源:igfitidea点击:

Handling api calls in Redux with Axios

javascriptreactjspromisereduxaxios

提问by Steinar

Good evening everybody!

晚上好大家!

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.

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

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.

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

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

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

Any help will be greatly appreciated.

任何帮助将不胜感激。

Here's the output from the console.

这是控制台的输出。

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

回答by Phi Nguyen

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

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

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

回答by HeonAle

You can do this with thunk. https://github.com/gaearon/redux-thunk

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

You can dispatch an action in your thenand it will update state when it gets a response from the axios call.

您可以在您的操作中分派一个操作,then当它从 axios 调用获得响应时,它将更新状态。

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

回答by duhaime

I took care of this task like so:

我像这样处理了这个任务:

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

回答by krankuba

I also think the best way to do this is by redux-axios-middleware. The setup can be a bit tricky as your store should be configured in a similar way:

我也认为最好的方法是通过 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();

And your action creators now look like this:

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

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

回答by Shyjal Raazi

The best way to solve this is by adding redux middlewares http://redux.js.org/docs/advanced/Middleware.htmlfor handling all api requests.

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

https://github.com/svrcekmichal/redux-axios-middlewareis a plug and play middleware you can make use of.

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