将reducer分配给嵌套状态属性?

时间:2016-12-03 20:45:19

标签: reactjs redux react-redux

使用下面的react / redux设置:

index.js

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import App from './components/app';
import configureStore from './store';

let initialState = {
  foods: {
    apple: {
      selected: false,
      flavors: {
        sweet: true,
        salty: false
      }
    },
    potatoChips: {
      selected: false,
      flavors: {
        sweet: false,
        salty: true
      }
    }
  },
  drinks: {
    < some other object >
  }
}

let store = configureStore(initialState);

render(
  <Provider store={store}>
    <App/>
  </Provider>,
  document.getElementById('app')
)

store.js

import { applyMiddleware, compose, createStore } from 'redux';
import rootReducer from './root-reducer';
import logger from 'redux-logger';
import thunk from 'redux-thunk';

let finalCreateStore = compose(
  applyMiddleware(thunk, logger())
)(createStore)

let defInitialState = < same object as initialState above >

export default function configureStore(initialState = defInitialState){
  return finalCreateStore(rootReducer, initialState)
}

根reducer.js

import { combineReducers } from 'redux';
import appleReducer from './apple-reducer';
import potatoChipsReducer from './potato-chips-reducer';


const rootReducer = combineReducers({
  foods.apple: appleReducer,
  foods['potatoChips']: potatoChipsReducer
  // HOW DO I DO THE ABOVE ASSIGNMENT?
})

export default rootReducer

我可以将减速器指定给state.foods.apple,就像我在上面root-reducer.js中尝试的那样吗?或者我应该以不同的方式解决这个问题?

extratextsothisquestionisntallcodeandcanbesubmitted

1 个答案:

答案 0 :(得分:3)

您可以嵌套combineReducers

示例:https://jsfiddle.net/2rhs2m9y/

const foodsReducer = combineReducers({
  apple: appleReducer,
  potatoChips: potatoChipsReducer,
})

const rootReducer = combineReducers({
  foods: foodsReducer,
})

因此,您的appleReducer只会收到foods.apple树作为其状态,等等。

你可以选择做(这基本上就是combineReducers为你做的事):

const rootReducer = combineReducers({
  foods: (state, action) => ({
    apple: appleReducer(state.apple, action),
    potatoChips: potatoChipsReducer(state.potatoChips, action),
  }),
})