useLive()
异步渲染由远端触发的数据变更。
将 useSuspense() + useSubscription() 合二为一的 hook。
useLive() 会响应数据变更,仅在必要时重新渲染。
用法
Ticker
AssetPrice
import { useLive } from '@data-client/react'; import NumberFlow from '@number-flow/react'; import { getTicker } from './Ticker'; function AssetPrice({ productId }: Props) { const ticker = useLive(getTicker, { productId }); return ( <dl className="stats"> <div> <dt>{productId}</dt> <dd> <NumberFlow value={ticker.price} format={{ style: 'currency', currency: 'USD' }} /> </dd> </div> </dl> ); } interface Props { productId: string; } render(<AssetPrice productId="BTC-USD" />);
行为
条件依赖
将 null 作为任意 Data Client hook 的第二个参数,表示“什么都不做”。没有路径参数或查询参数的 RestEndpoint 则用 {} 代替,比如 enabled ? {} : null。
// todo could be undefined if id is undefined
const todo = useLive(TodoResource.get, id ? { id } : null);
React Native
使用 React Navigation 时,如果数据被视为过时,useLive() 会在获得焦点时触发获取。 useLive() 还会分别在获得焦点/失去焦点时订阅/取消订阅。
在隐藏的 <Activity> 中,useLive() 会取消订阅。显示时会重新订阅。示例
类型
- 类型
- 使用泛型
function useLive(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): Denormalize<typeof endpoint.schema>;
function useLive<
E extends EndpointInterface<
FetchFunction,
Schema | undefined,
undefined
>,
Args extends readonly [...Parameters<E>] | readonly [null],
>(
endpoint: E,
...args: Args
): E['schema'] extends Exclude<Schema, null>
? Denormalize<E['schema']>
: ReturnType<E>;
示例
比特币价格(轮询)
当使用了 useLive 的组件被渲染时,getTicker 会每隔 pollFrequency
毫秒获取一次。
探索 nextjs 示例
暂停隐藏的标签页
让标签页在 <Activity> 中保持挂载。只有显示的标签页会轮询。
Ticker
AssetPrice
Markets
import React from 'react'; import AssetPrice from './AssetPrice'; const products = ['BTC-USD', 'ETH-USD', 'SOL-USD']; function Markets() { const [shown, setShown] = React.useState(products[0]); return ( <> <header className="appHeader"> <h1 className="appTitle">Markets</h1> <div className="segmented" role="group" aria-label="Product"> {products.map(productId => ( <button key={productId} aria-pressed={productId === shown} onClick={() => setShown(productId)} > {productId.split('-')[0]} </button> ))} </div> </header> {products.map(productId => ( <React.Activity key={productId} mode={productId === shown ? 'visible' : 'hidden'} > <AssetPrice productId={productId} /> </React.Activity> ))} </> ); } render(<Markets />);
隐藏的标签页会保留其状态,但它的 Effect 会停止。如果没有其他组件订阅它的价格,轮询就会停止。显示时,轮询会恢复。如果上次获取早于 pollFrequency,会立即获取。
隐藏的标签页仍会渲染,因此每个标签页都会在显示之前获取其价格。切换标签页时,价格会直接显示,不会出现加载状态。