2016-06-17 31 views
0
gesendet

Ich habe gerade mit Redux experimentieren und ich weiß, dass Middleware ist unerlässlich, um Ajax Anrufe zu machen. Ich habe Redux-Thunk- und Axios-Paket separat installiert und versucht, mein Ergebnis als Status zu haken und das Ajax-Ergebnis meiner Komponente zu rendern. Meine Browser-Konsole zeigt jedoch einen Fehler an und mein Reducer konnte die Nutzlast nicht erfassen.Redux Aktion Ajax Ergebnis nicht zu Reduzierer

Der Fehler:

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

Dieser Teil meines Codes ist und wie die Middleware angeschlossen:

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

meine Aktion:

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 } 
     }); 
     }) 
    ); 
    } 
} 

Minderer:

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; 
    } 
} 

Sie den Zustand routes hat eine Größe von 0, aber die Aktion Nutzlast hat Array von 3.

my latest action

schätzen wirklich jede mögliche Hilfe, Dank sehen.

Antwort

4

Es sieht so aus, als ob Sie eine unnötige Absendung in Ihrer Aktion haben, und Ihre request scheint nicht an der richtigen Stelle instanziiert zu werden. Ich glaube, Ihre Aktion sollte sein:

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