我实际上正在尝试使用 redux-promise,当我在操作中向我的 api 发送请求时,我收到此错误。
我看到有一个演讲主题出现了同样的错误,但我没有在回复中找到我的问题解决方案。
这是我的代码:
./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
<小时/>
调用的操作:
./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,但遇到了同样的错误。
你有什么想法吗?或者也许我误会了? 谢谢
最佳答案
在 actions 中创建 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
}
})
}
关于javascript - redux-promise 错误 : Actions must be plain objects. 使用自定义中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38980913/