如何基于最新Normalizr文档为Redux定义对象数组Schema?
Let’s walk through creating a proper Normalizr schema for your device data, optimized for Redux’s flat state structure.
Step 1: Import Normalizr Utilities
First, pull in the necessary functions from Normalizr:
import { schema, normalize } from 'normalizr';
Step 2: Define the Device Entity Schema
Each device in your response has a unique device_id—we’ll use this as the identifier for our entity schema (instead of the default id field):
const deviceSchema = new schema.Entity('devices', {}, { idAttribute: 'device_id' // Explicitly set the unique key for devices });
Step 3: Create the Array Schema
Since your API returns an array of device objects, wrap the entity schema in an array schema. You can use either the explicit schema.Array constructor or the shorthand array syntax:
// Explicit array schema const devicesArraySchema = new schema.Array(deviceSchema); // Or shorthand (equivalent) const devicesArraySchema = [deviceSchema];
Step 4: Normalize Your API Response
Pass your raw API data into the normalize function along with the array schema to get the Redux-friendly structure:
const rawApiResponse = [ { "device_id": "1234", "network_status": "Offline", "status": "Yes", "frequency": 50 }, { "device_id": "12345", "network_status": "online", "status": "no", "frequency": 123 }, { "device_id": "12346", "network_status": "online", "status": "no", "frequency": 423 } ]; const normalizedData = normalize(rawApiResponse, devicesArraySchema);
What the Normalized Output Looks Like
The result will be a flat structure ideal for Redux:
entities: A nested object wheredevicesare stored by theirdevice_idresult: An array ofdevice_ids preserving the original order of your API response
Example snippet of the normalized output:
{ entities: { devices: { "1234": { "device_id": "1234", "network_status": "Offline", "status": "Yes", "frequency": 50 }, "12345": { "device_id": "12345", "network_status": "online", "status": "no", "frequency": 123 }, "12346": { "device_id": "12346", "network_status": "online", "status": "no", "frequency": 423 } } }, result: ["1234", "12345", "12346"] }
This structure makes it easy to update, access, and reference individual devices in your Redux store without deep nesting.
内容的提问来源于stack exchange,提问作者dankthreads

