Redux 操作 ajax 结果未分派到 reducer

Redux action ajax result not dispatched to reducer

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

错误:

Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.

这是我的部分代码以及中间件的连接方式:

//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。

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

看起来您的操作中有不必要的分派,而且您的 request 看起来没有在正确的位置实例化。我相信你的行动应该是:

export function saveSettings(form = { inputFrom: null, inputTo: null }) {
  return (dispatch) => {
    axios.get(url).then((response) => {
      ...
      dispatch({
        type: SAVE_SETTINGS,
        payload: { form: form, routes: routes }
      });
    });
  };
}