reducers 在 redux 中得到 Function 而不是 Object,有什么问题?

IT技术 javascript reactjs redux
2021-05-14 02:24:04

我的 react 和 redux 项目出错了。我没有找到如何解决它。

这是错误信息:

The previous state received by the reducer has unexpected type of "Function". Expected argument to be an object with the following keys: "posts", "sidebar"

错误信息

代码:

商店.js:

import { createStore, applyMiddleware } from 'redux'
import logger from 'redux-logger'
import thunk from 'redux-thunk'

import reducers from '../reducers/index'

const middleware = process.env.NODE_ENV === 'production' ? [ thunk ] : [ thunk, logger() ]

const store = createStore(reducers, applyMiddleware(...middleware),  window.devToolsExtension ? window.devToolsExtension() : f => f)

export default store

减速器/ index.js:

import { combineReducers } from 'redux'
import posts from './posts'
import sidebar from './sidebar'

const rootReducer = combineReducers({
    posts,
    sidebar
})

export default rootReducer

减速器/posts.js:

import {
    RECEIVE_POSTS,
    RECEIVEING_POSTS
} from '../containers/index'

const initialState = {
    posts: [],
    post: {},
    message: 'done'
}

const post = (state = initialState, action) => {
    switch (action.type) {
        case RECEIVE_POSTS:
            return Object.assign({}, state, {
                posts: action.posts
            })
            break
        case RECEIVEING_POSTS:
            return Object.assign({}, state, {
                message: 'loading'
            })
        default:
            return state
    }
}

export default post

减速器/sidebar.js

import {
    TOGGLE_SIDEBAR
} from '../containers/index'

const initialState = {
    show: true
}

const sidebar = (state = initialState, action) => {
    switch (action.type) {
        case TOGGLE_SIDEBAR:
            return Object.assign({}, state, {
                show: ! state.show
            })
            break
        default:
            return state
    }
}

export default sidebar

我阅读了 redux 示例,但我不知道我的代码有什么问题。它只是抛出错误。

那些代码很像 redux 的例子!!!

谢谢你的耐心。

3个回答

这是过去工作的旧版本:

const store = createStore(reducers, applyMiddleware(...middleware),  window.devToolsExtension ? window.devToolsExtension() : f => f)

现在您必须将其转换为:

const store = redux.createStore(
    rootReducer,
    initialState,
    redux.compose(
        redux.applyMiddleware(...middleware),
        window.devToolsExtension ? window.devToolsExtension() : f => f
    )
);

我知道...

在PARAMS是第二createStoreinitialState不是中间件..

发生错误是因为您的状态对象的键必须与您传递给的对象的键匹配combineReducers检查此文档以获取更多详细信息combineReducers