使用自定义异步中间件派发 - Redux Thunk - react Router

Use Custom Async middleware to dispatch - Redux Thunk - react Router

我正在尝试使用 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 位置,我只是将 roder 从第 2 个参数换到第 3 个参数,它完成了,我的最终代码是:const store = createStore( combineReducers({ app: reducer, routing: routerReducer, launch: launchReducer }), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), applyMiddleware(ReduxThunk), );

感谢帮助,抱歉英语不好!

您以错误的方式配置商店。 createStore 接收 3 个参数(reducer、preloadedState、enhancer)。因为您在代码中发送 3,所以 'applyMiddleware(ReduxThunk)' 被视为预加载状态。

检查此 link 以了解在使用 redux-thunk 等增强器时如何配置 redux-devtools:https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup