---
name: "useDevicesProps"
mode: "api"
versionRequirements:
  - { name: "@ray-js/panel-sdk", version: "1.16.0" }
title: "useDevicesProps"
summary: "多设备管理 useDevicesProps Hook 说明，介绍如何按设备 key 读取多台设备的 DP 状态，并通过精确 selector 减少无效重渲染。"
---

## useDevicesProps

> [VERSION] @ray-js/panel-sdk >= 1.16.0

> 💡 使用前需挂载 SdmDevicesProvider 并配置关联设备映射。
> 性能优化（最佳实践）：
> 1. 强烈建议始终将 selector 的颗粒度精确到具体的功能点，例如 useDevicesProps(props => props.main?.switch_led)，避免全量订阅导致无关设备或无关功能点改变时引发无效的重渲染。
> 2. 如果 selector 必须返回包含多个字段的对象，由于默认使用浅比较（shallow equal），只要提取的值未发生改变就不会触发重渲染。必要时也可传入 equalityFn 进行深度定制。

### 描述

获取关联设备的功能点状态集合数据。

### 参数

`Params`

| 参数 | 类型 | 必填 | 描述 |
| --- | --- | --- | --- |
| `selector` | `(devicesProps: { [key: string]: DpState }) => DpValue;` | 是 | 选择器函数，入参为所有关联设备的 props 集合对象。   key 为设备标识，value 为该设备的功能点键值对 |
| `equalityFn` | `(prev: DpValue, next: DpValue) => boolean;` | 否 | 自定义比较函数，返回 true 则不触发重渲染，默认 shallow equal |

### 返回值

类型: `DpValue`

匹配选择器的功能点值，类型由 selector 返回值自动推导

**`type` DpValue**

```typescript
export type DpValue = boolean | number | string;
```

### 引用对象

##### `type` DpState

功能点状态对象，key 为功能点 code，value 为功能点值

```typescript
export type DpState = Record<string, DpValue>;
```

##### `type` DpValue

功能点值类型，可能为 boolean、number、string

```typescript
export type DpValue = boolean | number | string;
```


### 示例代码

#### 仅订阅单台设备的特定状态

```tsx
import { useDevicesProps } from '@ray-js/panel-sdk';

export default function Lamp1Switch() {
  // 仅在 lamp1 的 switch_led 变化时重渲染
  const switchLed = useDevicesProps(p => p?.lamp1?.switch_led);

  return <Text>lamp1 开关：{switchLed ? 'ON' : 'OFF'}</Text>;
}
```

#### 自定义 rerender

```tsx
// useDevicesProps 内部已针对 selector 返回值做 shallow equal 浅比较，无特殊场景时无需传入 equalityFn。
import { useDevicesProps } from '@ray-js/panel-sdk';

export default function PowerMap() {
  const powerMap = useDevicesProps(
    p => {
      const map: Record<string, boolean> = {};
      Object.keys(p ?? {}).forEach(k => { map[k] = !!p[k]?.switch_led; });
      return map;
    },
    (prev, next) => JSON.stringify(prev) === JSON.stringify(next)
  );

  return (
    <View>
      {Object.keys(powerMap).map(k => (
        <Text key={k}>{k}: {powerMap[k] ? 'ON' : 'OFF'}</Text>
      ))}
    </View>
  );
}
```
