一、基本方式:
a) 定义你的动作创建者:
import axios from 'axios';
//Post list
export const FETCH_DATA = 'FETCH_DATA';
export const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
export const FETCH_DATA_FAILURE = 'FETCH_DATA_FAILURE';
const ROOT_URL = 'foo/bar';
export function fetchPosts() {
const request = axios({
method: 'get',
url: `${ROOT_URL}/data`,
headers: []
});
return {
type: FETCH_DATA,
payload: request
};
}
export function fetchDataSuccess(data) {
return {
type: FETCH_DATA_SUCCESS,
payload: data
};
}
export function fetchDataFailure(error) {
return {
type: FETCH_DATA_FAILURE,
payload: error
};
}
b) 定义减速器:
import { FETCH_DATA, FETCH_DATA_SUCCESS, FETCH_DATA_FAILURE } from 'pathToActionTypes';
export default function(state = INITIAL_STATE, action) {
let error;
switch(action.type) {
case FETCH_DATA: // start fetching and set fetching = true
return { ...state, dataObj: {data:[], error: null, fetching: true} };
case FETCH_DATA_SUCCESS:// return data and set fetching = false
return { ...state, dataObj: {data: action.payload, error:null, fetching: false} };
case FETCH_DATA_FAILURE:// return error and set fetching = false
error = action.payload || {message: action.payload.message}; // message could be provided if network/server down errors
return { ...state, dataOjb: {data: [], error: error, fetching: false} };
default:
return state;
}
}
c) 容器:
import { connect } from 'react-redux'
import { fetchData, fetchDataSuccess, fetchDataFailure } from 'pathToActionCreators';
import FooBarComponent from '../components/foo_bar_component';
const mapStateToProps = (state) => {
return {
fooBar: state.dataObj.data
};
}
const mapDispatchToProps = (dispatch) => {
return {
fetchData: () => {
dispatch(fetchData()).then((response) => {
!response.error ?
dispatch(fetchDataSuccess(response.payload.data)) :
dispatch(fetchDataFailure(response.payload.data));
});
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(FooBarComponent);
二、高级方法:像 nross83 在这里自己定义中间件:
Redux: Using async middlewares vs dispatching actions on success functions
三、懒惰的方式:使用 redux-promise-middleware,因为它在内部和外部将 FETCH_DATA 扩展到 FETCH_DATA_PENDING、FETCH_DATA_FULLFILLED、FETCH_DATA_REJECTED。请查看https://github.com/pburtchaell/redux-promise-middleware/tree/master/examples上的示例
希望这可能会有所帮助。