首页 文章

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

提问于
浏览
1

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

enter image description here

我看到有一个演讲主题同样的错误,但我没有在回答中发现我的问题解决 .

So this is my code :

./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'))

./reducers/app-reducer.js

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


const rootReducer = combineReducers({
    user: user
})

export default rootReducer

action whose called :

./actions/user-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 回答

  • 1

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

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

    像这样改变你的商店:

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

    并设置axios使用调度:

    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
          }
       })
    }
    

相关问题