@ably-labs/react-hooks 中文文档教程

发布于 3年前 浏览 21 项目主页 更新于 3年前

ably-react-hooks

使用惯用的、易于使用的 React Hooks 在你的 React 应用程序中使用 Ably!

使用此包,您可以:

  • Interact with Ably channels using a react hook.
  • Send messages via Ably using the channel instances the hooks provide
  • Get notifications of user presence on channels
  • Send presence updates

挂钩提供了与 Ably 交互的简化语法,并管理 Ably SDK 实例的生命周期,以便您在 React 组件重新渲染时注意订阅和取消订阅频道和事件。

Installation

这些钩子作为 ES6 模块发布,因此您可以在 React 代码中使用 import 语法。

npm install --save @ably-labs/react-hooks

这可以使用 create-react-app 开箱即用 - 您可以立即使用该包。

Ably channels and API keys

为了使用这些钩子,您需要一个 Ably API 密钥。 如果您尚未注册,可以立即注册一个免费的 Ably 帐户。 拥有 Ably 帐户后:

  1. Log into your app dashboard.
  2. Under “Your apps”, click on “Manage app” for any app you wish to use for this tutorial, or create a new one with the “Create New App” button.
  3. Click on the “API Keys” tab.
  4. Copy the secret “API Key” value from your Root key, we will use this later when we build our app.

强烈建议您使用令牌身份验证,这将需要超出本自述文件范围的服务器端代码。 在下面的示例中,我们直接在标记中使用 API 密钥,这用于*仅本地开发并且不应用于生产代码并且不应< /strong> 致力于您的存储库。

Usage

使用 npm 将包添加到项目后,您可以在 react 代码中使用挂钩。

首先添加对挂钩的引用

import { configureAbly, useChannel } from "@ably-labs/react-hooks";

然后您需要使用 configureAbly 函数创建 Ably JavaScript SDK 的实例。

configureAbly({ key: "your-ably-api-key", clientId: generateRandomId() });

configureAbly 匹配 Ably SDK 的方法签名 - 并且需要 stringAblyClientOptions。 您可以使用此配置对象来设置您的 API 密钥,或者像往常一样设置 tokenAuthentication。 如果您想使用 usePresence 挂钩,您需要明确提供一个 clientId

完成此操作后,您可以在代码中使用 hooks。 最简单的示例如下:

const [channel] = useChannel("your-channel-name", (message) => {
    console.log(message);
});

每次将消息发送到 your-channel-name 时,它都会被记录到控制台。 您可以对这些消息做任何您需要做的事情。

useChannel

useChannel 钩子可以让你订阅一个频道并从中接收消息。

```javascript
const [channel, ably] = useChannel("your-channel-name", (message) => { 控制台日志(消息); });

Both the channel instance, and the Ably JavaScript SDK instance are returned from the useChannel call.

`useChannel` really shines when combined with a regular react `useState` hook - for example, you could keep a list of messages in your app state, and use the `useChannel` hook to subscribe to a channel, and update the state when new messages arrive.

javascript const [消息,updateMessages] = useState([]); const [channel] = useChannel("你的频道名称", (message) => { updateMessages((prev) => […prev, message]); });

// 将消息转换为列表项以在 React 组件中呈现 const messagePreviews = messages.map((msg, index) =>

  • {msg.data.someProperty}
  • );

    `useChannel` supports all of the parameter combinations of a regular call to `channel.subscribe`, so you can filter the messages you subscribe to by providing a `message type` to the `useChannel` function:
    

    javascript
    const [channel] = useChannel("your-channel-name", "test-message", (message) => { 控制台日志(消息); // 仅记录使用 test-message 消息类型发送的消息 });

    The `channel` instance returned by `useChannel` can be used to send messages to the channel. It's just a regular Ably JavaScript SDK `channel` instance.
    

    javascript channel.publish("test-message", { text: "message text" });

    ## usePresence
    
    The usePresence hook lets you subscribe to presence events on a channel - this will allow you to get notified when a user joins or leaves the channel.
    

    javascript const [presenceData, updateStatus] = usePresence("你的频道名称");

    // 将存在数据转换为要呈现的列表项
    const peers = presenceData.map((msg, index) =>

  • {msg.clientId}: {msg.data}
  • );

    `usePresence` returns an array of presence messages - again each message is a regular Ably JavaScript SDK `presenceMessage` instance.
    
    You can optionally provide a string when you `usePresence` to set an initial `presence data` string.
    

    javascript const [presenceData, updateStatus] = usePresence("your-channel-name", "initial state");

    The `updateStatus` function can be used to update the presence data for the current client:
    

    javascript updateStatus("新状态"); ```

    新状态将被发送到频道,订阅该频道的任何其他客户端将立即收到更改通知。

    ably-react-hooks

    Use Ably in your React application using idiomatic, easy to use, React Hooks!

    Using this package you can:

    • Interact with Ably channels using a react hook.
    • Send messages via Ably using the channel instances the hooks provide
    • Get notifications of user presence on channels
    • Send presence updates

    The hooks provide a simplified syntax for interacting with Ably, and manage the lifecycle of the Ably SDK instances for you taking care to subscribe and unsubscribe to channels and events when your react componenets re-render.

    Installation

    The hooks ship as an ES6 module, so you can use the import syntax in your react code.

    npm install --save @ably-labs/react-hooks
    

    This works out of the box using create-react-app - and you can use the package immediately.

    Ably channels and API keys

    In order to use these hooks, you will need an Ably API key. If you are not already signed up, you can sign up now for a free Ably account. Once you have an Ably account:

    1. Log into your app dashboard.
    2. Under “Your apps”, click on “Manage app” for any app you wish to use for this tutorial, or create a new one with the “Create New App” button.
    3. Click on the “API Keys” tab.
    4. Copy the secret “API Key” value from your Root key, we will use this later when we build our app.

    It is strongly recommended that you use Token Authentication, this will require server side code that is outside of the scope of this readme. In the examples below we use an API key directly in the markup, this is for *local development only and should not be used for production code and should not be committed to your repositories.

    Usage

    Once you've added the package using npm to your project, you can use the hooks in your react code.

    Start by adding a reference to the hooks

    import { configureAbly, useChannel } from "@ably-labs/react-hooks";
    

    Then you need to use the configureAbly function to create an instance of the Ably JavaScript SDK.

    configureAbly({ key: "your-ably-api-key", clientId: generateRandomId() });
    

    configureAbly matches the method signature of the Ably SDK - and requires either a string or an AblyClientOptions. You can use this configuration object to setup your API keys, or tokenAuthentication as you normally would. If you want to use the usePresence hook, you'll need to explicitly provide a clientId.

    Once you've done this, you can use the hooks in your code. The simplest example is as follows:

    const [channel] = useChannel("your-channel-name", (message) => {
        console.log(message);
    });
    

    Every time a message is sent to your-channel-name it'll be logged to the console. You can do whatever you need to with those messages.

    useChannel

    The useChannel hook lets you subscribe to a channel and receive messages from it.

    ```javascript
    const [channel, ably] = useChannel("your-channel-name", (message) => { console.log(message); });

    Both the channel instance, and the Ably JavaScript SDK instance are returned from the useChannel call.
    
    `useChannel` really shines when combined with a regular react `useState` hook - for example, you could keep a list of messages in your app state, and use the `useChannel` hook to subscribe to a channel, and update the state when new messages arrive.
    

    javascript const [messages, updateMessages] = useState([]); const [channel] = useChannel("your-channel-name", (message) => { updateMessages((prev) => […prev, message]); });

    // Convert the messages to list items to render in a react component const messagePreviews = messages.map((msg, index) =>

  • {msg.data.someProperty}
  • );

    `useChannel` supports all of the parameter combinations of a regular call to `channel.subscribe`, so you can filter the messages you subscribe to by providing a `message type` to the `useChannel` function:
    

    javascript
    const [channel] = useChannel("your-channel-name", "test-message", (message) => { console.log(message); // Only logs messages sent using the test-message message type });

    The `channel` instance returned by `useChannel` can be used to send messages to the channel. It's just a regular Ably JavaScript SDK `channel` instance.
    

    javascript channel.publish("test-message", { text: "message text" });

    ## usePresence
    
    The usePresence hook lets you subscribe to presence events on a channel - this will allow you to get notified when a user joins or leaves the channel.
    

    javascript const [presenceData, updateStatus] = usePresence("your-channel-name");

    // Convert presence data to list items to render
    const peers = presenceData.map((msg, index) =>

  • {msg.clientId}: {msg.data}
  • );

    `usePresence` returns an array of presence messages - again each message is a regular Ably JavaScript SDK `presenceMessage` instance.
    
    You can optionally provide a string when you `usePresence` to set an initial `presence data` string.
    

    javascript const [presenceData, updateStatus] = usePresence("your-channel-name", "initial state");

    The `updateStatus` function can be used to update the presence data for the current client:
    

    javascript updateStatus("new status"); ```

    The new state will be sent to the channel, and any other clients subscribed to the channel will be notified of the change immediately.

      我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
      原文