0

在减速器上处理 AJAX 错误的正确位置是什么?(如果你使用 Redux 加上redux-promise中间件)。

至少应该有 3 种类型的错误:网络错误/超时、未找到数据或 500 内部服务器错误。我试图处理它的方式是:

  if (action.error) {
    return state;
  }

所以整个减速器是:

export default function(state = [], action) {

  if (action.error) {
    return state;
  }

  switch (action.type) {
    case FETCH_WEATHER:
      return [action.payload.data].concat(state);
    default:
      return state;
  }

}

以上是处理AJAX 调用可能出现的所有类型错误的正确方法吗?如果没有,那么什么是正确的方法?

4

1 回答 1

1

一、基本方式:

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上的示例

希望这可能会有所帮助。

于 2017-05-26T04:04:49.723 回答