ngrx/store分发Action时是否复制全状态?大状态性能咨询
Great question—this is a super common concern when working with NgRx, especially when you've got large state slices like availableProducts that you don't want to waste resources recreating unnecessarily. Let's break this down clearly:
The Short Answer
When you dispatch an action that only affects your cart slice (e.g., adding an item to the cart), your profile and availableProducts state slices will NOT be recreated. They'll remain as references to their original memory locations. Only the cart slice will be updated with a new immutable object.
The Longer Explanation
NgRx (and Redux, its parent pattern) relies on a core principle of immutable state updates, but that doesn't mean the entire state tree gets rebuilt on every action. Here's how it works:
- Each of your reducers (
profile,availableProducts,cart) only handles actions relevant to their own slice of state. - For actions that a reducer doesn't care about (like a cart-related action for the
availableProductsreducer), the reducer simply returns the existing state reference instead of creating a new object. - Only the reducer that matches the action (your
cartreducer in this case) will create a new immutable version of its slice (e.g., a new cart array/object with the added item).
For example, your availableProducts reducer might look something like this:
function availableProductsReducer(state = initialState, action: Action) { switch (action.type) { // Only handle actions specific to availableProducts here case 'LOAD_PRODUCTS_SUCCESS': return action.payload; // New state object only when needed default: return state; // Return original reference for all other actions } }
Since the default case returns the original state reference, availableProducts never gets recreated unless an action specifically targets it. This means even if availableProducts is huge, it won't impact performance when you're updating the cart.
Key Takeaway
As long as you follow NgRx's immutable update patterns (always return new state only for the slice you're modifying, and return the original state for all other actions), you don't have to worry about unnecessary state duplication or performance hits from large unrelated slices.
内容的提问来源于stack exchange,提问作者qbolt

