Taro开发微信小程序保持登录状态(本地存储)

Taro

一、Taro官网链接
Taro是 由凹凸实验室倾力打造的 一个开放式跨端跨框架解决方案,支持使用React、Vue.js、Nerv等框架来开发小程序、H5、react Native等应用。

二、思考一下,如果你第一次使用这款应用的时候需要登录,那么你第二次肯定不会想再登录一次了,所以依托微信这个母体,小程序可以在进入页面时直接加载本地的一些信息,所以我们可以在useEffect中调用。
————————————————
三、https://taro-docs.jd.com/taro/docs/apis/storage/setStorage
在这里插入图片描述

四、直接上代码:

 useEffect(() => {
    
    
    Taro.getStorage({
    
    
      key: 'token',
      success: function (res) {
    
    
        console.log(res.data)
        const token = res.data
        deirectLogin(token)
      }
    })

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

// 从缓存里获取到token 直接登录
  const deirectLogin = async (token: string) => {
    
    
    queryUserSupplierRegister(token)
  }
  //登录 步骤      ......4  very good
  const reqLogin = async (encryptoPasswd: string) => {
    
    
    try {
    
    
      const {
    
     success = false, result = {
    
    } } = await req.post('xxxxx.xxxxx.login', {
    
     mobile: trim(phone), password: encryptoPasswd })
      if (success) {
    
    
        if (result.error && result.error.code) {
    
    
          showMsg(result.error)
          result.error.code === -34111 && setLimitFull(true)
        } else {
    
    
          const {
    
     businessType = -1, mobile, token } = result

          if (token) {
    
    
            // 解决每次打开页面都需要重新登录的问题
            Taro.setStorage({
    
    //本地存储token
              key: "token",
              data: token
            })
            Taro.setStorage({
    
    //本地存储mobile
              key: "mobile",
              data: mobile
            })
            setData('token', token)
            setData('mobile', mobile)
            showMsg('登录成功')
            queryUserSupplierRegister(token)//登录页面的业务代码,此处不多赘述
          } else {
    
    
            showMsg('登录失败!')
          }
        }
      }

五、退出登录时,需要清除本地存储中的 token
https://taro-docs.jd.com/taro/docs/apis/storage/clearStorage
在这里插入图片描述
代码块:

 const handleMassage = (e) => {
    
    
    Taro.clearStorage()//清除本地缓存token
  }
  return <WebView src={
    
    jumpUrl} onMessage={
    
    handleMassage} />

总结

本地存储就显得比较简单易懂了,当用户登录成功后你接收到服务器返回的数据后利用Taro.setStorage()进行本地存储即可,用户退出登录的时候需要 Taro.clearStorage()。

猜你喜欢

转载自blog.csdn.net/wangbaobao512/article/details/126873123
今日推荐