官方包 · 框架
React Native 与 Expo 的实时 WebSocket hooks
在 React Native 与 Expo 上使用 React 包的 hooks:应用进入后台时关闭连接、回到前台再自动连上,任意大小的数据都能发送,还能通过 Hibira Push 发送推送通知。
@hibira-io/react-nativenpm ↗GitHub ↗
- 在 React Native 版 pusher-js 上使用 useEvent、usePresence、useTrigger 和 useStream,支持 Expo SDK 50 及以上和原生 React Native 0.70 及以上。
- 应用在后台超过 30 秒就会关闭连接,放在口袋里的手机不会一直占用套餐的连接数。
- triggerChunked() 和 useChunkedEvent() 会把超过 Free 套餐 4 KB 上限的数据拆开再拼回,useHibiraPush() 则为设备注册推送通知。
登录后,示例代码会自动填入您的集群主机。 登录
安装
npx expo install @hibira-io/react-native pusher-js @react-native-community/netinfo配置
import { HibiraProvider } from '@hibira-io/react-native'; export default function App() { return ( <HibiraProvider appKey={process.env.EXPO_PUBLIC_HIBIRA_KEY} options={{ wsHost: 'ws.hibira.io', channelAuthorization: { endpoint: 'https://api.example.com/hibira/auth', transport: 'ajax' }, }} > <Home /> </HibiraProvider> ); }使用
import { useEvent, usePresence } from '@hibira-io/react-native'; function Orders() { const [orders, setOrders] = useState([]); useEvent('orders', 'order.created', (order) => setOrders((list) => [order, ...list])); const { count } = usePresence('presence-dashboard'); return <OrderList orders={orders} watching={count} />; }
开始之前
- 私有频道和 presence 频道需要后端提供授权端点,用应用密钥签名订阅,做法与 pusher-js 相同。
- 连接你电脑上的服务器时,wsHost 要填它的局域网地址,不能填 localhost,因为在手机上 localhost 指的是手机本身。
请使用控制台中应用的 Key;Secret 只放在你的服务器上。频道、事件与授权端点的用法与 Pusher 完全相同。 免费创建账号 →