使用normalizr规范化服务器响应并存储至Redux状态的技术咨询
Hey there! Let's break down exactly how to normalize your nested directory structure using Normalizr—this will make storing and managing the data in Redux way more efficient.
Step 1: Install Normalizr
First, make sure you have the package installed:
npm install normalizr # or yarn add normalizr
Step 2: Define Your Schema
The key here is creating a recursive schema for your directories, since each directory can have subdirectories of the same type.
import { schema, normalize } from 'normalizr'; // Create a schema for directories—note the recursive reference to itself for subdirectories const directorySchema = new schema.Entity('directories', { subdirectories: [directorySchema] // Recursively handle nested subdirectories }, { idAttribute: 'id' // Explicitly set the unique identifier (defaults to 'id' if omitted) });
Step 3: Normalize the Raw Data
Take your server's raw response array and pass it to the normalize function, along with the schema (wrapped in brackets since the root is an array):
// Your raw server response const rawServerData = [ { "name":"parches", "id":1, "numberOfbundles":0, "subdirectories":[ { "name":"satelite", "id":2, "numberOfbundles":3, "subdirectories":[] } ] }, { "name":"layout", "id":3, "numberOfbundles":0, "subdirectories":[ { "name":"clientes", "id":4, "numberOfbundles":3, "subdirectories":[ { "name":"demo", "id":5, "numberOfbundles":3, "subdirectories":[] } ] } ] } ]; // Normalize the data const normalizedData = normalize(rawServerData, [directorySchema]);
Step 4: Understand the Normalized Output
The normalizedData will have two main parts:
result: An array of the root directory IDs ([1, 3]in this case)entities: A flat object where all directories are stored by their ID, with nestedsubdirectoriesconverted to arrays of IDs instead of full objects
Here's what the output looks like:
{ result: [1, 3], entities: { directories: { 1: { name: "parches", id: 1, numberOfbundles: 0, subdirectories: [2] }, 2: { name: "satelite", id: 2, numberOfbundles: 3, subdirectories: [] }, 3: { name: "layout", id: 3, numberOfbundles: 0, subdirectories: [4] }, 4: { name: "clientes", id: 4, numberOfbundles: 3, subdirectories: [5] }, 5: { name: "demo", id: 5, numberOfbundles: 3, subdirectories: [] } } } }
Step 5: Use in Redux
When storing this in Redux, you can:
- Merge
entities.directoriesinto your state (e.g.,state.directories) - Store
resultasstate.rootDirectoryIds(to track which directories are at the top level)
This flat structure makes it easy to:
- Update a single directory without traversing nested arrays
- Look up any directory by its ID quickly
- Avoid duplicate data in your store
内容的提问来源于stack exchange,提问作者David Rebe Garcia

