Redux动作ajax结果没有发送到reducer

时间:2016-06-17 15:46:56

标签: ajax reactjs redux redux-thunk axios

我只是尝试使用Redux,我知道中间件对于进行ajax调用至关重要。我已经分别安装了redux-thunk和axios包,并试图将我的结果挂钩为状态,并将ajax结果呈现给我的组件。但是我的浏览器控制台显示错误,我的reducer无法获取有效负载。

错误:

  

未捕获错误:操作必须是普通对象。使用自定义中间件进行异步操作。

这是我的代码的一部分以及如何连接中间件:

//after imports

const logger = createLogger({
  level: 'info',
  collapsed: true,
});

const router = routerMiddleware(hashHistory);

const enhancer = compose(
  applyMiddleware(thunk, router, logger),
  DevTools.instrument(),
  persistState(
    window.location.href.match(
      /[?&]debug_session=([^&]+)\b/
    )
  )

// store config here...

我的行动:

import axios from 'axios';

export const SAVE_SETTINGS = 'SAVE_SETTINGS';

const url = 'https://hidden.map.geturl/?with=params';
const request = axios.get(url);

export function saveSettings(form = {inputFrom: null, inputTo: null}) {
  return (dispatch) => {
    dispatch(request
      .then((response) => {
        const alternatives = response.data.alternatives;
        var routes = [];
        for (const alt of alternatives) {
          const routeName = alt.response.routeName;
          const r = alt.response.results;
          var totalTime = 0;
          var totalDistance = 0;
          var hasToll = false;
          // I have some logic to loop through r and reduce to 3 variables
          routes.push({
            totalTime: totalTime / 60,
            totalDistance: totalDistance / 1000,
            hasToll: hasToll
          });
        }
        dispatch({
          type: SAVE_SETTINGS,
          payload: { form: form, routes: routes }
        });
      })
    );
  }
}

减速器:

import { SAVE_SETTINGS } from '../actions/configure';

const initialState = { form: {configured: false, inputFrom: null, inputTo: null}, routes: [] };

export default function configure(state = initialState, action) {
  switch (action.type) {
    case SAVE_SETTINGS:
      return state;
    default:
      return state;
  }
}

您可以看到状态routes的大小为0,但操作有效内容的数组为3。

my latest action

非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:4)

您的操作中似乎有不必要的调度,而[] why? test this is a test triggered ['test', 'this is a test'] THIS IS WORKING [] why? #this is from getPms.bot_run() ['test', 'this is a test']#this is from def inboxReader THIS IS WORKING 看起来并未在正确的位置进行实例化。我相信你的行动应该是:

request