【发布时间】:2018-06-12 06:15:32
【问题描述】:
我正在尝试使用 redux thunk 分发异步操作。
但我的代码不起作用,控制台只是向我抛出错误
Error: Actions must be plain objects. Use custom middleware for async actions.
好吧,这是我的代码:
import React from 'react';
import ReactDOM from 'react-dom';
import 'babel-polyfill';
import ReduxThunk from 'redux-thunk';
import { createStore, combineReducers,applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { syncHistoryWithStore, routerReducer } from 'react-router-redux';
import App, { reducer } from './AppContainer';
import {launchReducer} from './modules/Financeiro/Lancamentos/reducer/launchReducer';
import {Rotas} from './routes';
// Add the reducer to your store on the `routing` key
const store = createStore(
combineReducers({
app: reducer,
routing: routerReducer,
launch: launchReducer
}),
applyMiddleware(ReduxThunk),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
);
// Create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store);
document.getElementById('app').style['min-height'] = '100vh';
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
{Rotas.map(rota => (
<Route path={rota.path} component={App}>
<IndexRoute component={rota.component} />
</Route>)
)}
</Router>
</Provider>,
document.getElementById('app') // eslint-disable-line comma-dangle
);
而我的动作代码是这样的:
export const newLaunch = (obj) => async (dispatch) => {
delete obj.idLaunch_headerOrigin
let resp = await APIService('http://localhost:3000/launch/newLaunch', obj, 'POST')
dispatch({type: SET_LAUNCH_HEADER_ORIGIN, payload: resp.response})
}
在组件中,我只是导入动作并从 react-redux 放入连接,我用“this.props.newLaunch(obj)”调用它
编辑:
我的错误出现在 createStore 中,create store 接收到 3 个参数,我在将 prelaoders 放置在 enchances 位置时出错了,我只是将骑手从第 2 个参数换到第 3 个参数就完成了,我的最终代码是:const store = createStore(
combineReducers({
app: reducer,
routing: routerReducer,
launch: launchReducer
}),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
applyMiddleware(ReduxThunk),
);
感谢您的帮助,英语不好请见谅!
【问题讨论】:
-
您必须为您的操作添加
Promise支持,因为您的 API 返回一个承诺。redux-promise应该可以帮到你。 -
但是 redux-thunk 提供这个问题不是吗?或者 redux-promise 有另一个功能。在我所有的项目中,我只使用了 redux-thunk,这就是我调度异步操作所需要的全部
-
我知道redux的promise是返回一个promise,dispatch返回一个函数!但在我的操作中,我使用 async/await 来等待响应并从 API 的响应中调度某个属性。
标签: reactjs react-router react-redux redux-thunk react-router-redux