微信小程序参数解析问题---小记

360 阅读1分钟

1,参数解析失败

  wx.redirectTo({
                    url: `/pages/authorize/authorize?redirect=${params}` 
                });

这种参数解析如果params是类似于/pages/authorize/authorize?name=111, 这种在微信小程序中利用options取值的时候会被切割,解决办法就是利用编码,encodeURIComponentdecodeURIComponent处理一下

2.拉起微信用户授权,(必须先调用getUserProfile 在login之前)

wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        wx.showLoading({
          title: '加载中'
        });
         wx.login({
			success:function(){
			}
})
        }

getUserProfile必须是用户主动获取,必须先在login前获取到用户信息,这里的用户信息是完整的用户微信信息, 微信改版后可以通过logincode后端直接换取openid已经unionId

3逻辑跳转修改

var pages = getCurrentPages();
        var currentPage = pages[pages.length - 1];
        var route = '/' + currentPage.route;
        if (route !== "/pages/index/index") {

            var params = encodeURIComponent(`${route}${urlParamParse(currentPage.options)}`)
            console.log(`redirect=`+`${route}${urlParamParse(currentPage.options)}`,`${urlParamParse(currentPage.options)}`);
          
                wx.redirectTo({
                    url: `/pages/authorize/authorize?redirect=${params}` 
                });
            
           
        }
  1. 第一如果currentPage没有及时刷新,可以调用currentPage.onLoad事件触发,

  2. 第二如果前者还不行,可以加wx.nextTick()触发onload,个人感觉类似于setTimeout,这里遇到了个兼容问题,华为手机完全不支持,所以选择wx.redirectTo关闭当前页面,

function urlParamParse (options) {
  let str = '';
  console.log(options,151515)
  for (let key in options) {
    str += `&${key}=${options[key]}`
  }
  str = str.replace(/&/, '?');
  return str;
 }

参数解析如果for in 循环对象的时候,最好利用[]取值,不建议用obj.key,