Redux与Ducks文件夹结构:是否支持嵌套文件夹?
Great question! The original Ducks pattern doesn’t explicitly cover nested folder structures, but it’s totally adaptable to apps with multi-level modules—perfect for your payroll-related features. Here’s how to structure it effectively:
You can create a dedicated payroll directory within your root ducks folder, then split submodules into their own subdirectories. Each submodule follows the Ducks principle (action types, action creators, and reducer in a single file), while a top-level index.js in the payroll folder ties everything together.
Example structure:
src/ ducks/ payroll/ core/ # Shared payroll logic (e.g., pay period setup, base salary calculations) payrollCore.js deductions/ # Submodule: tax, insurance, and other deductions deductions.js bonuses/ # Submodule: performance bonuses, overtime pay bonuses.js index.js # Combines submodule reducers and exports shared actions # Other modules (e.g., benefits, attendance) benefits/ ...
No—you absolutely can (and should) split the payroll logic into smaller, focused reducers for each submodule. This keeps your code maintainable, testable, and aligned with Ducks’ modular spirit.
Here’s how to implement this:
Each submodule has its own duck file:
payroll/deductions/deductions.jswould contain action types likeADD_TAX_DEDUCTION, action creators likeaddTaxDeduction(), and a reducer that manages the deductions slice of state.payroll/bonuses/bonuses.jsdoes the same for bonus-related logic.
Combine submodule reducers in
payroll/index.js:import { combineReducers } from 'redux'; import coreReducer from './core/payrollCore'; import deductionsReducer from './deductions/deductions'; import bonusesReducer from './bonuses/bonuses'; // Combine all payroll sub-reducers into a single payroll reducer export const payrollReducer = combineReducers({ core: coreReducer, deductions: deductionsReducer, bonuses: bonusesReducer }); // Export all action creators from submodules for easy access elsewhere export * from './core/payrollCore'; export * from './deductions/deductions'; export * from './bonuses/bonuses';Add the payroll reducer to your root reducer:
In your rootducks/index.js(or wherever you combine root reducers):import { combineReducers } from 'redux'; import { payrollReducer } from './payroll'; import { benefitsReducer } from './benefits'; export const rootReducer = combineReducers({ payroll: payrollReducer, benefits: benefitsReducer // ... other modules });
- Clear separation of concerns: Each submodule handles its own logic, making it easier to debug and update.
- Reusability: Shared logic in
payroll/corecan be used across all payroll submodules. - Consistency: Every submodule follows the Ducks pattern, so your team can navigate code predictably.
This structure stays true to the core ideas of Ducks while scaling to support complex, nested modules like your payroll system.
内容的提问来源于stack exchange,提问作者Android Noob

