mini-auth-小程序认证钩子使用.md 4.3 KB


description: "小程序 useAuth hook 使用指南"

useAuth Hook 使用指南

基本导入

import { useAuth } from '@/utils/auth'

使用方式

在组件中使用:

const { user, login, logout, register, updateUser, isLoading, isLoggedIn } = useAuth()

API 说明

属性 类型 说明
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>
  )
}

注意事项

  1. 使用 useAuth 的组件必须包裹在 AuthProvider
  2. 所有认证相关的 API 调用都会自动处理 token 和错误提示
  3. 用户信息会自动缓存到本地存储,避免重复请求
  4. 退出登录会自动清除本地存储的 token 和用户信息
  5. 更新用户信息后会自动同步到本地存储