跳到主要内容

useRequestSubscribeMessage

请求订阅(设备)消息

何时使用

当需要请求订阅消息时

API

const { subscribe, subscribeDevice } = useRequestSubscribeMessage();

参数说明

返回值说明

参数类型说明
subscribePromiseAction<string, SuccessCallbackResult>请求订阅消息
subscribeDevicePromiseAction<ExcludeOption<Taro.requestSubscribeDeviceMessage.Option>, SuccessCallbackResult>订阅设备消息接口

代码演示

wechat/useRequestSubscribeMessage/index
import React from 'react';
import { useRequestSubscribeMessage, useModal } from 'taro-hooks';
import DemoContent from '@src/components/DemoContent';
import { Button } from '@taroify/core';

export default () => {
const { subscribe, subscribeDevice } = useRequestSubscribeMessage();
const show = useModal({ mask: true, title: '订阅结果', showCancel: false });

const subscribeId = 'jeNEwprDztjgwq0BI1raBmcJ7Sw1ldt-8lRi-7jXeyY';

const handleSubscribe = async () => {
let content = '订阅成功';
try {
const { [subscribeId]: result } = await subscribe([subscribeId]);
content = result !== 'accept' ? '订阅失败' : content;
} catch (e) {
content = e.errMsg || e.message;
}
show({ content });
};

const handleSubscribeDevice = async () => {
let content = '订阅成功';
try {
// 这里的数据是mock的. 真实配置需要在平台设置绑定
const { [subscribeId]: result } = await subscribeDevice({
tmplIds: [subscribeId],
snTicket: ('' + Math.random()).replace('0.', ''),
sn: ('' + Math.random()).replace('0.', ''),
modelId: ('' + Math.random()).replace('0.', ''),
});
content = result !== 'accept' ? '订阅失败' : content;
} catch (e) {
content = e.errMsg || e.message;
}
show({ content });
};

return (
<DemoContent>
<Button
block
color="primary"
onClick={handleSubscribe}
className="gap"
shape="square"
>
订阅消息
</Button>
<Button
block
color="primary"
onClick={handleSubscribeDevice}
shape="square"
>
订阅设备消息
</Button>
</DemoContent>
);
};

Hook 支持度

微信小程序H5ReactNative
✔️