useRequireAuth.ts 623 B

1234567891011121314151617181920212223242526272829
  1. import { useEffect } from 'react'
  2. import Taro from '@tarojs/taro'
  3. import { useAuth } from './useAuth'
  4. /**
  5. * 要求认证的hook
  6. * 如果用户未登录,则重定向到登录页
  7. */
  8. export const useRequireAuth = () => {
  9. const { isLoggedIn, isLoading } = useAuth()
  10. useEffect(() => {
  11. if (!isLoading && !isLoggedIn) {
  12. Taro.showToast({
  13. title: '请先登录',
  14. icon: 'none',
  15. duration: 1500
  16. })
  17. setTimeout(() => {
  18. Taro.redirectTo({
  19. url: '/pages/login/index'
  20. })
  21. }, 1500)
  22. }
  23. }, [isLoggedIn, isLoading])
  24. return { isLoggedIn, isLoading }
  25. }