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

标签 reactjs redux react-redux

我有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/

相关文章:

javascript - 使用 Redux 和 Router 进行 React - 不是渲染组件

reactjs - React Hook "useParams"在既不是 React 函数组件也不是自定义 React Hook 函数的函数 "fetchMentors"中被调用

javascript - 未从 Redux 中的子组件获取 props

javascript - react native + 终极版 : How to render <ListView/> upon clicking a button?

javascript - redux、react-redux、redux-thunk 之间有什么区别?

javascript - redux 存储中的状态发生变化但组件在 View 中没有变化

javascript - 功能组件中的默认功能 Prop

reactjs - componentDidMount 中使用的 setState 值未反射(reflect)在 Enzyme 测试中

javascript - react 原生如何使用 Prop 自定义样式

typescript - thunkAPI.getState 不是函数 : Error with reduxtoolkit and jest