具有相同名称的嵌套状态

Nested state with the same name

我正在实现与 redux 的反应,我得到了一个同名的嵌套状态(见图)

这是我的减速器:

function helps(state = {
  isFetching: false,
  items: []
}, action) {
  switch (action.type) {
    case types.HELPS_FEED_REQUEST:
      return Object.assign({}, state, {
        isFetching: true
      });
    case types.HELPS_FEED_SUCCESS:
      return Object.assign({}, state, {
        isFetching: false,
        items: [
          ...state.items,
          ...action.items
        ]
      });
    default:
      return state;
  }
}

const rootReducer = combineReducers({
  helps
});

export default rootReducer;

index.js减速器:

import {combineReducers} from 'redux';
import help from './helpReducer';
import helps from './helpsReducer';


const rootReducer = combineReducers({
    help,
    helps
});

export default rootReducer;

我的问题是:为什么我没有只有一个 "helps" 带有 isFetching 和 items 的状态?有什么明显的我想念的吗?

编辑:

显然是因为我使用的是combine reducer。因此,如果我将函数名称更改为,例如 helps_feed,状态将是:

helps
-- helps_feed

为什么combineReducers做嵌套状态?

configureStore.js

import { createStore, applyMiddleware, compose } from 'redux';
import rootReducer from '../reducers';
import createSagaMiddleware, {END} from 'redux-saga';
import helpSagas from '../sagas/helpSaga';

export default function configureStore(initialState) {
  const rootSagas = [
    helpSagas
  ];
  const sagaMiddleWare = createSagaMiddleware();

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

  store.runSaga = sagaMiddleWare.run(...rootSagas);
  store.close = () => store.dispatch(END);
  return store;
}

combineReducers 使用您传递给它的 reducer 创建一个新对象,这就是您嵌套状态的原因。

要解决此问题,请在不使用 combineReducers 的情况下导出减速器,因为您没有组合任何减速器。

function helps(state = {
  isFetching: false,
  items: []
}, action) {
  switch (action.type) {
    case types.HELPS_FEED_REQUEST:
      return Object.assign({}, state, {
        isFetching: true
      });
    case types.HELPS_FEED_SUCCESS:
      return Object.assign({}, state, {
        isFetching: false,
        items: [
          ...state.items,
          ...action.items
        ]
      });
    default:
      return state;
  }
}

export default helps;

具有多个 combineReducer 的场景。

rootReducer.js

import auth from './auth'
import trainer from './trainer/trainerReducer'
import athlete from './athlete/athleteReducer'

const rootReducer = combineReducers({
    auth,
    trainer,
    athlete
});

trainerReducer.js

import { combineReducers } from 'redux'
import manageAthletes from './manageAthletes'
import manageRoutines from './manageRoutines'

const trainerReducer = combineReducers({
    manageRoutines,
    manageAthletes
});

export default trainerReducer;

运动员减速机

import trainer from './trainer'
import routine from './routine'

const athleteReducer = combineReducers({
    trainer,
    routine
});

export default athleteReducer;