小程序-判断是否登录公用组件

javascript 复制代码
import type { FC, PropsWithChildren, ReactElement } from 'react';
import React, { useMemo } from 'react';
import Taro from '@tarojs/taro';

import useLoginState from '@/hooks/useLoginState';

interface WithSignInComponentProps extends PropsWithChildren {
  children: ReactElement;
  ignoreAuth?: boolean; // 是否强制忽略验证登录
  redirect?: string;
}

const WithSignInComponent: FC<WithSignInComponentProps> = ({
  children,
  ignoreAuth = false, // 是否强制忽略验证登录
  redirect // 跳转地址
}) => {
  const [, , action] = useLoginState();

  const eventRef = useMemo(() => children?.props?.onClick, [children?.props?.onClick]);

  const handleClick = async (e: Event) => {
    e.stopPropagation();
    try {
      const cookies = await action?.get();
      //本项目是存储的cookies,使用hooks----useLoginState能获取到
      const isLogin = !!(cookies && cookies?.length > 0);
      // 登陆判断
      if (ignoreAuth) {
        eventRef?.(e);
        return;
      }

      if (!isLogin) {
        await Taro.navigateTo({
          url: `登录的路由${
            redirect ? `?redirect=${encodeURIComponent(redirect)}` : ''
          }`
        });

        return;
      }
      eventRef?.(e);
    } catch {}
  };
  // @ts-ignore
  return React.cloneElement(children, { onClick: handleClick });
};

export default WithSignInComponent;

使用方式:

javascript 复制代码
//组件引用,放在了公共组件components下
import WithSignInComponent from '@/components/WithSignInComponent';
<WithSignInComponent>
	<div>测试登录</div>
</WithSignInComponent>
相关推荐
MoonMoonLee1 天前
小程序配置
小程序
2501_916007471 天前
苹果商店iOS应用上架费用全面解析:开发者计划与审核费用计算
android·ios·小程序·https·uni-app·iphone·webview
JQweryuiop1 天前
中小型游戏陪练工作室数字化管理实践:基于七彩屋电竞护航小程序订单、履约与绩效系统的落地复盘
大数据·游戏·小程序·架构
Ai-_Man1 天前
您您这可以把Mistral AI的多个会话比如说。左侧的多个会话一次性导出吗?不是单条会话里面的多次会对话。
人工智能·ai·小程序·电脑
2501_916008891 天前
如何实现iOS App代码混淆:SwiftShield使用指南
android·ios·小程序·https·uni-app·iphone·webview
微擎应用市场1 天前
简单拼车小程序系统:实现出行与物流资源的高效精准匹配
小程序
2501_916008891 天前
怎么用 Godot 导出 iOS 应用并上架 App Store?签名字段该填什么?
android·ios·小程序·https·uni-app·iphone·webview
2601_963870201 天前
基于springboot的综合网上购物商场系统
微信小程序·小程序·课程设计
2601_963869952 天前
力序健身房管理系统
微信小程序·小程序
一 乐2 天前
二手交易平台|基于springboot + vue二手交易平台(源码+数据库+文档)
java·数据库·vue.js·spring boot·小程序