我正在使用 redux-thunk
用于异步操作和 babel-polyfill
为了 promise 。我收到以下错误: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.jsimport 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);
最后,这是我的 reducer :
function statesReducer(state = null, action) {
switch (action.type) {
case RECEIVE_STATES:
return { ...state, states: action.states };
default:
return state;
}
}
最佳答案
我认为您的错误可能是由以下原因引起的:
我建议您安装 redux-logger 中间件并将其作为最后一个添加到您的商店中间件中,删除返回 thunk 时不需要的 promise 中间件。
通过这种方式,所有操作都记录在控制台中(前一个状态、当前操作、下一个状态),您可以调试您返回的未被 thunk 中间件“消化”的操作对象类型。
关于Redux-thunk 异步操作 : Use custom middleware for async actions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38930963/