import { useAuth } from '@/utils/auth'
在组件中使用:
const { user, login, logout, register, updateUser, isLoading, isLoggedIn } = useAuth()
| 属性 | 类型 | 说明 |
|---|---|---|
user |
User \| null |
当前登录用户信息 |
login |
(data: LoginRequest) => Promise<User> |
登录函数 |
logout |
() => Promise<void> |
退出登录函数 |
register |
(data: RegisterRequest) => Promise<User> |
注册函数 |
updateUser |
(userData: Partial<User>) => Promise<User> |
更新用户信息 |
isLoading |
boolean |
是否正在加载 |
isLoggedIn |
boolean |
是否已登录 |
const ProfilePage = () => {
const { user, isLoading } = useAuth()
if (isLoading) {
return <View>加载中...</View>
}
if (!user) {
return <View>请先登录</View>
}
return (
<View>
<Text>用户名: {user.username}</Text>
<Text>邮箱: {user.email}</Text>
</View>
)
}
const LoginPage = () => {
const { login } = useAuth()
const handleLogin = async (formData) => {
try {
const user = await login({
username: formData.username,
password: formData.password
})
// 登录成功后的处理
} catch (error) {
// 处理登录错误
}
}
}
const RegisterPage = () => {
const { register } = useAuth()
const handleRegister = async (formData) => {
try {
const user = await register({
username: formData.username,
password: formData.password,
email: formData.email
})
// 注册成功后的处理
} catch (error) {
// 处理注册错误
}
}
}
const ProfilePage = () => {
const { logout } = useAuth()
const handleLogout = async () => {
try {
await logout()
// 退出成功后会自动跳转到登录页
} catch (error) {
// 处理退出错误
}
}
}
const ProfilePage = () => {
const { user, updateUser } = useAuth()
const handleUpdateAvatar = async (avatarFileId) => {
if (user) {
const updatedUser = {
...user,
avatarFileId: avatarFileId
}
await updateUser(updatedUser)
}
}
}
const ProfilePage = () => {
const { user, logout, isLoading, updateUser } = useAuth()
const handleLogout = async () => {
try {
await Taro.showModal({
title: '退出登录',
content: '确定要退出登录吗?',
success: async (res) => {
if (res.confirm) {
await logout()
// 退出成功后会自动跳转到登录页
}
}
})
} catch (error) {
// 处理错误
}
}
const handleAvatarUpload = async (result) => {
try {
if (user) {
const updatedUser = {
...user,
avatarFileId: result.fileId
}
await updateUser(updatedUser)
Taro.showToast({ title: '头像更新成功', icon: 'success' })
}
} catch (error) {
Taro.showToast({ title: '更新失败', icon: 'none' })
}
}
if (isLoading) {
return <View className="flex justify-center items-center h-screen">加载中...</View>
}
if (!user) {
return (
<View className="flex justify-center items-center h-screen">
<Text className="mb-4">请先登录</Text>
<Button onClick={() => Taro.navigateTo({ url: '/pages/login/index' })}>
去登录
</Button>
</View>
)
}
return (
<View>
<Image src={user.avatarFile?.fullUrl} className="w-20 h-20 rounded-full" />
<Text>{user.username}</Text>
<Button onClick={handleLogout}>退出登录</Button>
</View>
)
}
useAuth 的组件必须包裹在 AuthProvider 内