我對異步操作使用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;
}
}
http://fiddle.jshell.net/josephj/e02Lcoee/ – zloctb