@tracio/react 包对核心 @tracio/sdk 进行了封装,提供符合 React 习惯的原语:一个用于挂载 agent 的 provider,以及若干将访客 ID 和识别结果连同加载与错误状态一并交给你的 Hook。
npm install @tracio/react @tracio/sdkreact(18 或 19)是一个 peer dependency,默认你的应用中已经安装了它。
用 <TracioProvider> 包裹你的应用。它会在首次渲染时挂载 TRACIO agent,并在 provider 卸载时自动调用 tracio.destroy()。
import { TracioProvider } from "@tracio/react"
function Root() { return ( <TracioProvider publicKey={process.env.NEXT_PUBLIC_TRACIO_KEY!}> <App /> </TracioProvider> )}| Prop | 类型 | 说明 |
|---|---|---|
publicKey | string | 你的公钥。从控制台中复制它。 |
config | TracioConfig | 完整的配置对象。其优先级高于下方的扁平标量属性。 |
endpoint | string | 自定义 API 端点(用于第一方代理的端点)。 |
scriptUrl | string | agent 脚本的自定义 URL(用于第一方代理的端点)。 |
debug | boolean | 向控制台输出详细的诊断日志。 |
timeoutMs | number | 在超时之前等待结果的时长(默认 15000)。 |
children | ReactNode | 必填 —— 需要包裹的 React 子树。 |
要么传入 publicKey 以及扁平标量,要么传入一个完整的 config 对象。当两者都提供时,以 config 为准。
返回稳定的访客标识符,连同加载与错误状态。
const { data, isLoading, error, isFetched, getId } = useVisitorId()// data: string | undefined — the visitorIdgetId() 会以命令式方式重新获取访客 ID。
返回完整的 TracioResult(访客 ID 加上机器人检测)。
const { data, isLoading, error, isFetched, getData } = useTracioResult()// data: TracioResult | undefinedopts.immediate 默认为 true。传入 { immediate: false } 可以推迟获取,直到你自己调用 getData() —— 在同意(consent)门控之后使用时很有用:
const { data, getData } = useTracioResult({ immediate: false })
function onConsent() { getData() // identify only after the user opts in}一个逃生舱口(escape hatch),返回底层实例以供高级用途。
const { tracio } = useTracio()import { TracioProvider, useVisitorId } from "@tracio/react"function App() { return ( <TracioProvider publicKey={process.env.NEXT_PUBLIC_TRACIO_KEY!}> <Page /> </TracioProvider> )}function Page() { const { data: visitorId, isLoading, error } = useVisitorId() if (isLoading) return <span>Loading…</span> if (error) return <span>Error: {error.message}</span> return <span>Visitor: {visitorId}</span>}@tracio/sdk API