【发布时间】: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 调用,还是应该在组件安装时获取它?