跳到主要内容

useLive()

异步渲染由远端触发的数据变更。

将 useSuspense() + useSubscription() 合二为一的 hook。

useLive() 会响应数据变更,仅在必要时重新渲染。

用法​

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 (
    <center>
      {productId}{' '}
      <NumberFlow
        value={ticker.price}
        format={{ style: 'currency', currency: 'USD' }}
      />
    </center>
  );
}
interface Props {
  productId: string;
}
render(<AssetPrice productId="BTC-USD" />);
结果
Store▶

行为​

条件依赖

将 null 作为任意 Data Client hook 的第二个参数,表示“什么都不做”。

// todo could be undefined if id is undefined
const todo = useLive(TodoResource.get, id ? { id } : null);
React Native

使用 React Navigation 时,如果数据被视为过时,useLive() 会在获得焦点时触发获取。 useLive() 还会分别在获得焦点/失去焦点时订阅/取消订阅。

类型​

function useLive(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): Denormalize<typeof endpoint.schema>;

示例​

比特币价格(轮询)​

当使用了 useLive 的组件被渲染时,getTicker 会每隔 pollFrequency 毫秒获取一次。

更多演示