1. 分析问题
1.1 初始代码
// 代码未测试
import Taro from '@tarojs/taro';
import React, { useEffect, useState, useRef } from 'react';
const Index = () => {
// 缓存当前页面的路由信息
const router = useRef<any>(null);
useEffec(() => {
router.current = Taro.getCurrentInstance()?.router;
init();
},[]);
const init = async () => {
try{
const msg = await xxx({
id: router.current?.params?.id
})
} catch (error) {
}
}
return <div></div>
};
export default Index;
1.2 个别机型会出现参数id取不到值(1%-5%的概率会出现)
- 参数id一定传过来了(通过同一个小程序码扫描,有成功的代表肯定有值)
1.3 能判断是Taro.getCurrentInstance()没有拿到实例导致
为什么个别机型没拿到实例其实是不解的
2. 解决问题
2.1. 更改点
修改点1:执行init放到useDidShow中
修改点2:初次未获取到实例,1s后重试
修改点3:获取实例增加getCurrentPages增加容错
2.2. 更改后代码
// 代码未测试
import Taro from '@tarojs/taro';
import React, { useEffect, useState, useRef } from 'react';
const Index = () => {
// 缓存当前页面的路由信息
const router = useRef<any>(null);
// 修改点 1
Taro.useDidShow(() => {
router.current = getRouterInfo();
if(router.current?.params?.id) {
init();
} else {
// 修改点 2
// 延迟1s中大概率是已经能拿到实例
setTimeout(()=>{
router.current = getRouterInfo();
init()
},1000)
}
});
// 修改点 3
const getRouterInfo = () => {
return Taro.getCurrentInstance()?.router || Taro.getCurrentPages().slice(-1)?.[0]?.options
}
const init = async () => {
try{
const msg = await xxx({
id: router.current?.params?.id
})
} catch (error) {
}
}
return <div></div>
};
export default Index;
3. 结束
Q1: 你怎么知道是id没传导致的呢?
A1: 自己去服务器捞日志,提示id未传。
Q2: 你咋知道是未获取到实例呢?
A2: 因为我新增一个字段把Taro.getCurrentInstance(),通过接口传给后端,失败的日志记录这个值是undefined
Q3: 你为什么这么解决呢?
Q3: 第一,获取参数的方式只有2种,getCurrentInstance和getCurrentPages,我两种都给它用上还不行嘛。第二,获取参数的时机,官方建议是放到useDidShow。第三,如果以上都失败了,我1s再请求,这会不可能再失败了吧
感谢观看啦