0

Redux を試してみたところ、ajax 呼び出しを行うにはミドルウェアが不可欠であることがわかりました。redux-thunk と axios パッケージを別々にインストールし、結果を状態としてフックして、ajax の結果をコンポーネントにレンダリングしようとしました。しかし、ブラウザー コンソールにエラーが表示され、リデューサーがペイロードを取得できませんでした。

エラー:

キャッチされていないエラー: アクションはプレーン オブジェクトである必要があります。非同期アクションにはカスタム ミドルウェアを使用します。

これは私のコードの一部であり、ミドルウェアがどのように接続されているかです:

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

私の最近の行動

本当にありがとうございました。

4

1 に答える 1

4

アクションに不要なディスパッチがあり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 }
      });
    });
  };
}
于 2016-06-17T16:48:05.740 に答える