跳到主要内容

useUserInfo

获取用户信息

何时使用

当需要获取用户信息展示时

提示

getUserInfo会默认在方法内检查授权. 若未授权会直接返回错误.
getUserProfile获取到的数据不包含openIdunionId
此外要注意获取用户信息接口经常会调整。所以内置逻辑不作为保证完全成功的依据
用户头像昵称获取规则已调整, 开发者若需要在界面中展示用户的头像昵称信息,可以通过<open-data>组件进行渲染,该组件无需用户确认

API

const [userInfo, { getUserInfo, getUserProfile }] = useUserInfo();

参数说明

返回值说明

参数类型说明
userInfoUserInfo用户信息对象
getUserProfilePromiseOptionalAction<ExcludeOption<Taro.getUserProfile.Option>, Taro.getUserProfile.SuccessCallbackResult>获取用户信息(点击生效, 且每次弹窗)
getUserInfoPromiseOptionalAction<ExcludeOption<Taro.getUserInfo.Option>, Taro.getUserInfo.SuccessCallbackResult>获取用户信息

代码演示

wechat/useUserInfo/index
import React from 'react';
import { useUserInfo, useLogin, useModal } from 'taro-hooks';
import DemoContent from '@src/components/DemoContent';
import { Button, Cell, Flex, Avatar } from '@taroify/core';

export default () => {
const [userInfo = {}, { getUserInfo, getUserProfile }] = useUserInfo();
const { login } = useLogin();

const show = useModal({ mask: true, title: '获取结果', showCancel: false });

const handleGetUserInfo = async () => {
let content = '获取成功';
try {
await login(true);
await getUserInfo({ lang: 'zh_CN', withCredentials: true });
} catch (e) {
content = e.errMsg || e.message;
}
show({ content });
};

return (
<DemoContent>
<Flex gutter={8} align="center" justify="center">
<Flex.Item span={4}>
<Avatar size="large" src={userInfo?.userInfo?.avatarUrl} />
</Flex.Item>
<Flex.Item span={20}>
<Flex flex-wrap="wrap" justify="center" direction="column">
<Flex.Item>昵称: {userInfo?.userInfo?.nickName}</Flex.Item>
<Flex.Item>性别: {userInfo?.userInfo?.gender}</Flex.Item>
</Flex>
</Flex.Item>
</Flex>
<Button
block
color="primary"
className="gap"
onClick={handleGetUserInfo}
shape="square"
>
获取用户信息
</Button>
<Button
block
color="primary"
className="gap"
onClick={() =>
getUserProfile({ lang: 'zh_CN', desc: '仅作为小程序展示使用' })
}
shape="square"
>
获取用户信息(包含敏感信息)
</Button>
{Object.keys(userInfo).length ? (
<Cell.Group clickable title="用户信息">
{Object.entries({ ...(userInfo?.userInfo ?? {}), ...userInfo }).map(
([key, value]) => (
<Cell key={key} title={key} brief={JSON.stringify(value)}></Cell>
),
)}
</Cell.Group>
) : (
<Cell>暂无信息</Cell>
)}
</DemoContent>
);
};

Hook 支持度

微信小程序H5ReactNative
✔️