我安装了redux-thunk,我认为我将其配置为文档。但仍然会收到错误:Actions must be plain objects. Use custom middleware for async actions.
动作:
import fetch from 'isomorphic-fetch'
export { get_all_posts } from '../utils/http_functions'
export function fetchAllPosts(){
return{
type: 'FETCH_ALL_POSTS'
}
}
export function receivedAllPosts(posts){
return{
type: 'RECEIVED_ALL_POSTS',
posts: posts
}
}
export function getAllPosts(){
return (dispatch) => {
dispatch(fetchAllPosts())
return fetch('/api/posts')
.then(response => response.json())
.then(json => {
dispatch(receivedAllPosts(json))
})
.catch(error => {
})
}
}
存储
import { createStore, applyMiddleware } from 'redux'
import rootReducer from '../reducers/index'
import thunk from 'redux-thunk'
const debugware = [];
if (process.env.NODE_ENV !== 'production') {
const createLogger = require('redux-logger');
debugware.push(createLogger({
collapsed: true
}));
}
export default function configureStore(initialState = {}){
const store = createStore(
rootReducer,
initialState,
window.devToolsExtension && window.devToolsExtension(),
applyMiddleware(thunk, ...debugware)
)
if (module.hot){
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers/index').default
store.replaceReducer(nextRootReducer)
})
}
return store
}
减速器:
export function posts(state = {}, action){
switch(action.type){
case 'RECEIVED_ALL_POSTS':
return Object.assign({}, state, {
'posts': action.posts
})
default:
return state
}
}
在server.js中,我使用代理服务器路由' / api /'请求我的后端服务:
app.all(/^\/api\/(.*)/, function api(req, res){
proxy.web(req, res, {
target: 'http://localhost:5000'
})
})
答案 0 :(得分:0)
因为在你的代码中:
const store = createStore(
rootReducer,
initialState,
window.devToolsExtension && window.devToolsExtension(),
applyMiddleware(thunk, ...debugware)
)
实际上未应用函数applyMiddleware(thunk, ...debugware)
。在createStore
:http://redux.js.org/docs/api/createStore.html
createStore(reducer, [preloadedState], [enhancer])
您的applyMiddleware
应作为第三个参数输入。
注意:评论中的解决方案是应用中间件的另一种方法。