redux-promise出错:操作必须是普通对象。使用自定义中间件

时间:2016-08-16 17:20:34

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

我实际上尝试使用redux-promise,当我在行动中向我的api发送请求时,我收到此错误。

enter image description here

我看到有一个演讲主题出现同样的错误,但我没有在回复中找到解决问题的方法。

所以这是我的代码:

./ app.js

import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import { Router, browserHistory } from 'react-router'
import reducers from './reducers/app-reducer'
import routes from './routes'

import promise from 'redux-promise'

const createStoreWithMiddleware = applyMiddleware(promise)(createStore);


ReactDOM.render(<Provider store={createStoreWithMiddleware(reducers)}>
                <Router history={browserHistory} routes={routes} />
                </Provider>, document.querySelector('.container'))

./减速器/ APP-reducer.js

import { combineReducers } from 'redux'
import user from  './user-reducer'


const rootReducer = combineReducers({
    user: user
})

export default rootReducer

其所谓的行动:

./动作/用户actions.js

import axios from 'axios'

export const UPDATE_TOKEN = 'UPDATE_TOKEN'
export const CREATE_SESSION = 'CREATE_SESSION'
export const CREATE_SESSION_ERROR = 'CREATE_SESSION_ERROR'

export function createSession(obj){

    if (typeof obj === 'string') {

        return {
            type: UPDATE_TOKEN,
            payload: obj
        }
    }
    else {
        axios.post('http://localhost:8080' + '/session', {
            data: {'Email': obj.email, 'Password': obj.password},
            headers: {'Content-Type': 'application/json'}
        }).then((response) => {
            return {
                type: CREATE_SESSION,
                payload: response.data
            }
        }).catch((error) => {
            return {
                type: CREATE_SESSION_ERROR,
                payload: error
            }
        })
    }
}

我也尝试使用redux-thunk,我得到同样的错误。

有人有想法吗?或者我可能误解了我的意思? 感谢

1 个答案:

答案 0 :(得分:1)

在动作中创建ajax调用时,应使用redux-thunk和compose。

import {createStore, applyMiddleware, compose} from "redux";
import thunk from 'redux-thunk';

像这样更改您的商店:

const createStoreWithMiddleware = compose(applyMiddleware(thunk))(createStore)(reducers);

并设置axios使用dispatch:

return (dispatch) => {
   axios.post('http://localhost:8080' + '/session', {
      data: {'Email': obj.email, 'Password': obj.password},
      headers: {'Content-Type': 'application/json'}
   }).then((response) => {
      dispatch ({
         type: CREATE_SESSION,
         payload: response.data
      })
   }).catch((error) => {
      return {
         type: CREATE_SESSION_ERROR,
         payload: error
      }
   })
}