74 lines
1.7 KiB
Plaintext
74 lines
1.7 KiB
Plaintext
---
|
|
title: 提供并读取记录
|
|
description: 使用 RecordProvider、useRecord 和 useFieldValue 构建记录感知组件。
|
|
order: 10
|
|
toc:
|
|
- id: provide-a-record
|
|
title: 提供记录
|
|
- id: read-a-record
|
|
title: 读取记录
|
|
- id: read-a-field
|
|
title: 读取字段
|
|
---
|
|
|
|
## 提供记录 {#provide-a-record}
|
|
|
|
在获得数据的边界挂载 Provider。`RecordProvider` 接受已经存在的非空记录;请求结果可能为空时,使用 `OptionalRecordProvider`。
|
|
|
|
```tsx
|
|
import { RecordProvider } from "@workspace/record"
|
|
|
|
function ProductScreen({ product }: { product: Product }) {
|
|
return (
|
|
<RecordProvider value={product}>
|
|
<ProductDetails />
|
|
</RecordProvider>
|
|
)
|
|
}
|
|
```
|
|
|
|
```tsx
|
|
import { OptionalRecordProvider } from "@workspace/record"
|
|
|
|
;<OptionalRecordProvider value={query.data}>
|
|
<ProductDetails />
|
|
</OptionalRecordProvider>
|
|
```
|
|
|
|
## 读取记录 {#read-a-record}
|
|
|
|
`useRecord` 在没有 Provider 或数据尚未加载时返回 `undefined`。
|
|
|
|
```tsx
|
|
function ProductDetails() {
|
|
const product = useRecord<Product>()
|
|
if (!product) return <p>Loading…</p>
|
|
|
|
return <h2>{product.name}</h2>
|
|
}
|
|
```
|
|
|
|
记录感知组件也可以接受可选的 `record` prop。显式记录优先于上下文,方便单独预览和测试组件。
|
|
|
|
```tsx
|
|
function ProductTitle({ record }: { record?: Product }) {
|
|
const product = useRecord({ record })
|
|
return product ? <h2>{product.name}</h2> : null
|
|
}
|
|
```
|
|
|
|
## 读取字段 {#read-a-field}
|
|
|
|
`useFieldValue` 支持直接字段、嵌套对象和数组数字段。路径使用点分隔。
|
|
|
|
```tsx
|
|
const city = useFieldValue<Customer, "address.city">({
|
|
source: "address.city",
|
|
defaultValue: "Unknown",
|
|
})
|
|
|
|
const firstSku = useFieldValue<Order, "items.0.sku">({
|
|
source: "items.0.sku",
|
|
})
|
|
```
|