2016-08-13 123 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

相关问题