具有相同名称

时间:2016-06-07 14:53:15

标签: reactjs redux react-redux

我正在实施与redux的反应,我得到一个具有相同名称的嵌套状态(见图片)

enter image description here

这是我的减速机:

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 reducer:

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


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

export default rootReducer;

我的问题是:为什么我不能只有一个"帮助" isFetching和items的状态?有什么明显的东西我不见了吗?

修改

显然,这是因为我正在使用联合减速机。因此,如果我将函数的名称更改为,例如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;
}

1 个答案:

答案 0 :(得分:2)

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

要修复它,请不使用combineReducers导出reducer,因为您没有组合任何reducer。

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;

包含多个combineReducers的场景。

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;

athleteReducer

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

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

export default athleteReducer;