修改react-boilerplate:将注入的reducers嵌套到store单个键下
Got it, let's sort this out so your container-specific reducers live neatly under a dedicated containers key instead of cluttering up the root state. Here's a step-by-step breakdown:
1. Modify the Root Reducer Setup
First, head to your src/reducers.js file. The original createReducer function spreads injected reducers directly into the root state—we'll adjust it to nest those reducers under a containers key using combineReducers again.
Before:
import { combineReducers } from 'redux'; import routeReducer from './route'; import languageProviderReducer from './languageProvider'; export function createReducer(injectedReducers = {}) { return combineReducers({ route: routeReducer, language: languageProviderReducer, ...injectedReducers, // Dumps container reducers directly into root state }); }
After:
import { combineReducers } from 'redux'; import routeReducer from './route'; import languageProviderReducer from './languageProvider'; export function createReducer(injectedReducers = {}) { return combineReducers({ route: routeReducer, language: languageProviderReducer, // Nest all injected container reducers under the "containers" key containers: combineReducers(injectedReducers), }); }
This changes your root state structure to:
{ route: routeReducerState, language: languageProviderReducerState, containers: { container1: container1ReducerState, container2: container2ReducerState, container3: container3ReducerState, } }
2. Update State Access in Components & Selectors
Any component or selector that was pulling state directly from the root needs to adjust its path to look inside containers.
Example: Before (in a container component)
const mapStateToProps = state => ({ userData: state.container1.userData, });
After:
const mapStateToProps = state => ({ userData: state.containers.container1.userData, });
Don’t forget to check your reselect selectors too—if any reference root-level container state, update those paths as well.
3. Verify Dynamic Injection & Hot Reloading
react-boilerplate’s injectReducer utility works by adding reducers to the injectedReducers object, which our updated createReducer now wraps into the containers key. Test that dynamic injection still works (e.g., load a lazy-loaded container and confirm its reducer shows up under state.containers).
Also, double-check hot reloading for reducers—make sure changes to container reducers reflect in the store without breaking the app.
Why This Helps
- Cleaner root state: Separates global app state (route, language) from container-specific state
- Avoids naming collisions: No more stress about a container's reducer name clashing with a global reducer
- Better organization: Groups all container state in one predictable spot
内容的提问来源于stack exchange,提问作者tacos_tacos_tacos

