【问题标题】:Multiple axios get requests React-Redux多个 axios 获取请求 React-Redux
【发布时间】:2018-03-27 14:01:03
【问题描述】:

我有一个 React-Redux 应用程序,想使用 axios 发出并发 API GET 请求。我将 url 作为参数传递给操作。我怎样才能实现它?它是一个 UI 组件,在单击 BU 和单击 BU 时具有与 API 不同的数据。

组件:

import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getParallelData } from '../../actions/index';

class BUBGContainer extends Component {
  componentDidMount() {
    this.props.getParallelData('https://localhost:3001/reports/bu-list');
    this.props.getParallelData('https://localhost:3001/reports/bg-list');
  }

  updateTabs(i) {
    if (i === 1) {
      this.props.bgTab = true;
      this.props.buTab = false;
    } else {
      this.props.bgTab = false;
      this.props.buTab = true;
    }
  }


  render() {
    return (
      <div className="col-md-3">
        <label htmlFor="bu-bg-select">BU/BG:</label>
        <ul id="bu-bg-select-tabs" className="nav nav-tabs">
          <li role="presentation" className={ 'active' } onClick={ this.updateTabs(0) }><a>BU</a></li>
          <li role="presentation" className={ 'active' } onClick={ this.updateTabs(1) }><a>BG</a></li>
        </ul>
        <select name="bubgSelect" id="bu-bg-select" className="form-control">{_.map(this.props.items, (item, index) => <option key={ index }>{item}</option>)}</select>
        <p className="help-block">Hold <kbd>ctrl</kbd> and click to select multiple items</p>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  items: state.bubgFetching.data.rows,
});

const mapDispatchToProps = dispatch => bindActionCreators({ getParallelData }, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(BUBGContainer);

我不知道如何编写一个动作来达到同样的效果。

我现在的动作是

export const getParallelData = url => (dispatch) => {
  dispatch(requestGetData());
  return axios.get(url)
    .then((response) => {
      dispatch(receiveGetData(response.data));
    })
    .catch((response) => {
      dispatch(receiveGetError(response.data));
    });
};

const requestGetData = () => ({ type: ACTION_TYPES.REQ_GET_DATA });

const receiveGetData = json => ({
  type: ACTION_TYPES.RECV_GET_DATA,
  data: json,
});

const receiveGetError = json => ({
  type: ACTION_TYPES.RECV_GET_ERROR,
  data: json,
});

我目前的减速机是

import _ from 'lodash';
import * as ACTION_TYPES from '../consts/action_types';

const initialState = {
  isLoading: false,
  data: [],
  error: false,
};

export const isFetchingGet = (state = initialState, action) => {
  const newState = _.cloneDeep(state);

  switch (action.type) {
    case ACTION_TYPES.RECV_GET_ERROR: {
      newState.isLoading = false;
      newState.data = action.data;
      newState.error = true;
      return newState;
    }

    case ACTION_TYPES.RECV_GET_DATA: {
      newState.isLoading = false;
      newState.data = action.data;
      newState.error = false;
      return newState;
    }

    case ACTION_TYPES.REQ_GET_DATA: {
      newState.isLoading = true;
      newState.error = false;
      return newState;
    }

    default:
      return state;
  }
};

这个link 说如何使用它,但不确定如何实现它。

【问题讨论】:

  • 运行 webapp 时会发生什么?你想让它做什么不同的事情?
  • 我不确定如何在我的操作中编写 axios.all。我应该修改我的代码以仅在切换选项卡时触发 api 调用,还是应该在组件安装时获取它?

标签: reactjs redux axios


【解决方案1】:

这是 Promise.all 的替代方案,专注于您的并发请求问题。只是相关部分:

componentDidMount() {
    const list = [ "bu-list, "bg-list" ];
    this.props.getParallelData( list );
}

export const getParallelData = list =>
    async ( dispatch ) => {
        dispatch( requestGetData() );
        try {
            const promiseArray = list.map( el =>
                 axios.get( `https://localhost:3001/reports/${ el }` ) );
            const response = await Promise.all( promiseArray );
            return dispatch( receiveGetData( response ) );
            // and map through response for data, or
            // const [ buList, bgList ] = await Promise.all( promiseArray );
            // return dispatch( receiveGetData( [ buList.data, bgList.data ] ) );
            // or whatever form you want to pass receiveGetData
        } catch ( error ) {
            return dispatch( receiveGetError( error ) );
        }
 };

【讨论】:

  • 引发错误。不变的违反。是因为承诺吗?我也 console.log 响应,它返回 undefined。
  • 我不知道您的应用程序的哪个部分出现此错误,但我对获取数据的答案进行了更多编辑。你可以通过查看 Promise.all 方法来塑造你的代码。有一个 axios.all 方法,但由于有一个 Promise.all ,所以不需要它。同样,我的回答是关于使用 axios 进行并行请求。如果您想使用,也许您应该根据此方法更改代码的其他部分。
  • 感谢 devserkan 的帮助。
【解决方案2】:

你应该试试 redux-thunk 或 redux-saga 中间件。 Thunk 是更简单的选择。

https://github.com/gaearon/redux-thunk

你也可以使用 async/await 我发现它比 Promise 更具可读性。

所以这就是交易。您将发送函数而不是在您的动作创建者中发送对象,而 redux-thunk 会自动为您做一些事情。

你会这样做:

export const getParallelData = url => {
  return async dispatch => {
    const request = axios.get(url);
    try {
      if (response && response.ok) {
        await dispatch({
          type: ACTION_TYPES.REQ_GET_DATA,
          payload: request
        )}
      } catch(err) {
        await dispatch({
         type: ACTION_TYPES.REQ_GET_DATA,
         payload: err.toString()
        )}
      }
};

希望这会有所帮助!

【讨论】:

  • 我确实有 thunk 设置。我会试试这个并报告回来。谢谢
猜你喜欢
  • 1970-01-01
  • 2021-11-23
  • 2017-10-14
  • 2017-12-11
  • 2019-10-20
  • 2023-03-12
  • 2019-02-08
  • 2018-12-02
  • 2018-11-14
相关资源
最近更新 更多