2016-08-13 124 views
5

我對異步操作使用redux-thunk,承諾使用babel-polyfill。我收到以下錯誤:Error: Actions must be plain objects. Use custom middleware for async actions.Redux-thunk異步操作:使用自定義中間件進行異步操作

我通過在我的中間件中包含redux-promise解決了此問題。我不確定爲什麼我必須使用redux-promise來解決此問題,因爲Redux文檔中的所有示例均使用babel-polyfill。我應該繼續使用redux-promise還是我可能在babel-polyfill有問題?

babel-polyfill包括在我的應用程序入口點:

import 'babel-polyfill'; 

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import { Provider } from 'react-redux'; 

import App from './components/App.jsx'; 
import store from './store.jsx'; 

ReactDOM.render(
    <Provider store={store}> 
     <App /> 
    </Provider> 
    , document.querySelector('.container')); 

UPDATE:

所以,如果我已經安裝了redux-thunk我檢查,以防萬一。它在我的package.json中。這裏是我的store.js

import thunkMiddleware from 'redux-thunk'; 
import promise from 'redux-promise' 

export default store = createStore(
    rootReducer, 
    defaultState, 
    applyMiddleware(
    thunkMiddleware, 
    promise 
) 
); 

這裏是action.js我的異步操作:

function receiveStates(json) { 
    return { 
     type: RECEIVE_STATES, 
     states: json.states, 
    }; 
} 

export function fetchStates(uuid) { 
    return dispatch => 
     fetch(`https://my-api.com/session/${uuid}`) 
     .then(response => response.json()) 
     .then(json => dispatch(receiveStates(json))); 
} 

這裏是我從調用組件動作:

fetchStates(sessionID) { 
    this.props.dispatch(fetchStates(sessionID)); 
} 
# I bind this function in component's constructor 
this.fetchStates = this.fetchStates.bind(this); 

最後,這是我的減速機:

function statesReducer(state = null, action) { 
    switch (action.type) { 
     case RECEIVE_STATES: 
      return { ...state, states: action.states }; 
     default: 
      return state; 
    } 
} 
+0

http://fiddle.jshell.net/josephj/e02Lcoee/ – zloctb

回答

0

聽起來像你還沒有安裝/設置redux-thunk

你通常的方式安裝NPM包:

npm install --save redux-thunk 

這裏是應用redux-thunk中間件

getStore.js

import { createStore, applyMiddleware } from 'redux' 
import thunk from 'redux-thunk' 

const getStore = ({combined, initial}) =>{ 
    var store = createStore(combined, initial, applyMiddleware(thunk)) 
    return store 
} 

export{ 
    getStore 
} 
+0

我更新了我的問題。謝謝。 – dzeno

3

的一個例子,我想你錯誤可能是由以下原因造成的:

  1. 你沒有從你的動作創建者返回一個thunk(一個返回調度函數的函數),這樣Thunk中間件就不會抓住它(也許你正在返回一個promise)
  2. 你還沒有安裝終極版 - 咚由dzeno

我建議你安裝了Redux記錄器中間件並將其添加到您的商店中間件作爲最後一個,除去承諾中間件其是否返回一個thunk你不需要的建議。 通過這種方式,所有操作都記錄在控制檯(以前的狀態,當前操作,下一個狀態)中,您可以調試返回的操作對象類型,而不是由thunk中間件「消化」。

+0

我更新了我的問題。謝謝。 – dzeno

+0

事實上,就我而言,我是在回覆一個承諾,而不是一個thunk – aeb0

相關問題