gpt4 book ai didi

reactjs - 嵌套 `combineReducers` 不允许在没有嵌套对象的情况下拥有状态

转载 作者:行者123 更新时间:2023-12-04 20:57:27 26 4
gpt4 key购买 nike

我有bookManageReducer.jsx:

import { combineReducers } from 'redux'
import {
REQUEST_BOOKS_PAGE,
RECEIVE_BOOKS_PAGE
} from '../constants/dashboardConstants'

const books = (state = [], action) => {
switch (action.type) {
case RECEIVE_BOOKS_PAGE:
return action.books
default:
return state
}
}

const booksState = (state = {isFetching: false}, action) => {
switch (action.type) {
case REQUEST_BOOKS_PAGE:
return {isFetching: true}
case RECEIVE_BOOKS_PAGE:
return {isFetching: true}
default:
return state
}
}
// ...
const booksManageReducer = combineReducers({ books, employees, employeesList, booksPagination, booksState })

export default booksManageReducer

我想要的是将所有中间 reducer 合并到根 reducer dashboardReducer.jsx:

import { combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux'
import booksManageReducer from './booksManageReducer'

const companyId = (state = {}, action) => {
return state
}

const dashboardReducer = combineReducers({booksManageReducer, companyId, routing: routerReducer})

export default dashboardReducer

产生这种状态:

Object {booksManageReducer: Object, companyId: 1, routing: Object}

而不是

Object {books: [], ..., companyId: 1, routing: Object}

当我尝试使用对象扩展运算符时:

const dashboardReducer = combineReducers({
...booksManageReducer, companyId, routing: routerReducer
})

它只是从状态中消失,并且 Object.assign 也不起作用。

最佳答案

不要将它们合并到 booksMangeReducer 中。相反,只需将它们全部导出为命名导出并立即组合所有 reducer :

export { 
books,
employees,
employeesList,
booksPagination,
booksState
};

然后将它们全部导入:

import { 
books,
employees,
employeesList,
booksPagination,
booksState
} from './booksManageReducer'

然后使用combineReducers将它们单独组合起来:

combineReducers({
books,
employees,
employeesList,
booksPagination,
booksState,
companyId,
routing: routerReducer
});

combineReducers 使用传递对象的键来构造状态。这将给出所需的层次结构。

与您正在做的事情类似的另一种方法可能是导出包含所有 reducer 本身的对象,然后导入该对象并传播它:

export default {
//books, employees, etc.
};

然后:

import reducers from './booksManageReducer';

最后:

combineReducers({
...reducers,
companyId,
routing: routerReducer
});

关于reactjs - 嵌套 `combineReducers` 不允许在没有嵌套对象的情况下拥有状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44621515/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com