2016-06-17 11 views
0

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

エラー:

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

my latest action

の配列は本当に、感謝を任意の助けに感謝しています。

答えて

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 } 
     }); 
    }); 
    }; 
} 
関連する問題