使用Axios处理Redux中的api调用

Ste*_*nar 21 javascript promise reactjs redux axios

晚上好大家!

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

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

我正在使用Axios和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
    };
}
Run Code Online (Sandbox Code Playgroud)

减速器

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;
  }
Run Code Online (Sandbox Code Playgroud)

零件

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);
Run Code Online (Sandbox Code Playgroud)

Phi*_*yen 31

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

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

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

export function getAllFlights(request) {
  console.log(request);
  return {
    type: FETCH_FLIGHT,
    payload: request
  };
}
Run Code Online (Sandbox Code Playgroud)

  • 我不明白这是如何工作的.你在哪里叫`axios.get`? (2认同)
  • @AlanSchapira使用`axios'`中的`import axios将其导入到您的文件中 (2认同)

Heo*_*Ale 6

您可以通过重击来实现。 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);});
    };
}
Run Code Online (Sandbox Code Playgroud)


Shy*_*azi 5

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

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


kra*_*uba 5

我还认为最好的方法是通过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();
Run Code Online (Sandbox Code Playgroud)

现在,您的动作创建者如下所示:

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'
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 你能在我如何从连接方法触发方法api的地方发布演示吗 (2认同)

duh*_*ime 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)))
  }
}
Run Code Online (Sandbox Code Playgroud)