You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于最新Normalizr文档为Redux定义对象数组Schema?

How to Define Normalizr Schema for Your Device API Response for Redux

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 where devices are stored by their device_id
  • result: An array of device_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:51:05