--- description: "小程序 useAuth hook 使用指南" --- # useAuth Hook 使用指南 ## 基本导入 ```typescript import { useAuth } from '@/utils/auth' ``` ## 使用方式 在组件中使用: ```typescript const { user, login, logout, register, updateUser, isLoading, isLoggedIn } = useAuth() ``` ## API 说明 | 属性 | 类型 | 说明 | |------|------|------| | `user` | `User \| null` | 当前登录用户信息 | | `login` | `(data: LoginRequest) => Promise` | 登录函数 | | `logout` | `() => Promise` | 退出登录函数 | | `register` | `(data: RegisterRequest) => Promise` | 注册函数 | | `updateUser` | `(userData: Partial) => Promise` | 更新用户信息 | | `isLoading` | `boolean` | 是否正在加载 | | `isLoggedIn` | `boolean` | 是否已登录 | ## 使用示例 ### 获取用户信息 ```typescript const ProfilePage = () => { const { user, isLoading } = useAuth() if (isLoading) { return 加载中... } if (!user) { return 请先登录 } return ( 用户名: {user.username} 邮箱: {user.email} ) } ``` ### 处理登录 ```typescript const LoginPage = () => { const { login } = useAuth() const handleLogin = async (formData) => { try { const user = await login({ username: formData.username, password: formData.password }) // 登录成功后的处理 } catch (error) { // 处理登录错误 } } } ``` ### 处理注册 ```typescript 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) { // 处理注册错误 } } } ``` ### 处理退出登录 ```typescript const ProfilePage = () => { const { logout } = useAuth() const handleLogout = async () => { try { await logout() // 退出成功后会自动跳转到登录页 } catch (error) { // 处理退出错误 } } } ``` ### 更新用户信息 ```typescript const ProfilePage = () => { const { user, updateUser } = useAuth() const handleUpdateAvatar = async (avatarFileId) => { if (user) { const updatedUser = { ...user, avatarFileId: avatarFileId } await updateUser(updatedUser) } } } ``` ### 完整示例 ```typescript 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 加载中... } if (!user) { return ( 请先登录 ) } return ( {user.username} ) } ``` ## 注意事项 1. 使用 `useAuth` 的组件必须包裹在 `AuthProvider` 内 2. 所有认证相关的 API 调用都会自动处理 token 和错误提示 3. 用户信息会自动缓存到本地存储,避免重复请求 4. 退出登录会自动清除本地存储的 token 和用户信息 5. 更新用户信息后会自动同步到本地存储