Redux-thunk异步操作:使用自定义中间件进行异步操作
我对异步操作使用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;
}
}
听起来像你还没有安装/设置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
}
我更新了我的问题。谢谢。 – dzeno
的一个例子,我想你错误可能是由以下原因造成的:
- 你没有从你的动作创建者返回一个thunk(一个返回调度函数的函数),这样Thunk中间件就不会抓住它(也许你正在返回一个promise)
- 你还没有安装终极版 - 咚由dzeno
我建议你安装了Redux记录器中间件并将其添加到您的商店中间件作为最后一个,除去承诺中间件其是否返回一个thunk你不需要的建议。 通过这种方式,所有操作都记录在控制台(以前的状态,当前操作,下一个状态)中,您可以调试返回的操作对象类型,而不是由thunk中间件“消化”。
http://fiddle.jshell.net/josephj/e02Lcoee/ – zloctb