【发布时间】:2016-12-20 05:38:39
【问题描述】:
我将redux-thunk 用于异步操作,babel-polyfill 用于承诺。我收到以下错误:Error: Actions must be plain objects. Use custom middleware for async actions.
我通过在我的中间件中包含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'));
更新:
所以我检查了是否安装了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;
}
}
【问题讨论】:
标签: redux react-redux redux-thunk