跳到主要内容

useAuthorize

直接调起用户授权信息、获取用户授权信息

何时使用

当需要在使用某些权限功能前进行授权或校验时

API

const {
authSetting,
subscriptionsSetting,
authorize,
get,
open
} = useAuthorize(option?);

参数说明

参数说明类型默认值
withSubscriptions是否同时获取用户订阅消息的订阅状态,默认不获取booleanfalse

返回值说明

返回值说明类型
authSetting用户授权结果AuthSetting & { mini: AuthSetting }
subscriptionsSetting用户订阅消息设置SubscriptionsSetting
open调起客户端小程序设置界面(withSubscriptions?: boolean) => Promise<OpenSettingSuccessCallbackResult>
get获取用户授权信息(withSubscriptions?: boolean) => Promise<GetSettingSuccessCallbackResult>
authorize提前向用户发起授权请求(scope: string, mini?: boolean) => Promise<General.CallbackResult>

代码演示

wechat/useAuthorize/index
import React from 'react';
import { useAuthorize, useModal } from 'taro-hooks';

import DemoContent from '@src/components/DemoContent';
import { Cell, Button } from '@taroify/core';

export default () => {
const show = useModal({ title: '授权结果', mask: true, showCancel: false });

const { authSetting, subscriptionsSetting, authorize, open } =
useAuthorize(true);

const handleAuth = async () => {
let content = '授权成功';
try {
await authorize('scope.userInfo');
} catch (e) {
content = '授权失败';
}
show({ content });
};

return (
<DemoContent>
{Object.keys(authorize).length ? (
[authSetting, subscriptionsSetting].map((auth) =>
Object.entries(auth).map(([key, value]) => {
return (
<Cell.Group clickable title={key} key={key}>
{['string', 'boolean'].includes(typeof value) ? (
<Cell key={key} title={'授权 - ' + key}>
{value}
</Cell>
) : (
Object.entries(value as {}).map(([subKey, subValue]) => (
<Cell key={subKey} title={'授权 - ' + subKey}>
{subValue}
</Cell>
))
)}
</Cell.Group>
);
}),
)
) : (
<Cell>暂无信息</Cell>
)}
<Button
block
color="primary"
className="gap"
onClick={open}
shape="square"
>
打开设置
</Button>
<Button
block
color="primary"
className="gap"
onClick={handleAuth}
shape="square"
>
授权
</Button>
</DemoContent>
);
};

Hook 支持度

微信小程序H5ReactNative
✔️