使用自定义异步中间件进行调度 - Redux Thunk - 反应路由器

时间:2018-01-02 14:24:56

标签: reactjs react-router react-redux redux-thunk react-router-redux

我正在尝试用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中,创建商店收到了3个参数,我错误地将prelaoders放在了enchances的地方,我只是将第二个到第三个参数的交换器交换完了,我的最终代码是:{{1} }

感谢你的帮助,为不好的英语而烦恼!

1 个答案:

答案 0 :(得分:0)

您正在以错误的方式配置商店。 createStore接收3个参数(reducer,preloadedState,enhancer)。因为您在代码中发送了3个“applyMiddleware(ReduxThunk)”&#39;正被视为preloadedState。

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