Taro 路由跳转预加载
使用场景
当我们从A页面跳转到B页面,小程序页面触发onLoad
会有一定延时,当请求的数据过大的时候,延迟时间较长,极大影响用户体验
解决方法
Taro 3 提供了Taro.preload
API,可以把需要预加载的内容作为参数传入,然后在新页面加载后通过Taro.getCurrentInstance().preloadData
获取到预加载的内容。
用法一:传递异步请求数据
// A 页面
// 调用跳转方法前使用 Taro.preload
Taro.preload(fetchSomething()) // 发送B页面所需数据的请求
Taro.navigateTo({ url: '/pages/B/B' })
// B 页面
componentWillMount () {
console.log(Taro.getCurrentInstance().preloadData) // 获取到数据
}
用法二:页面跳转之间的传参
// A 页面
Taro.preload('x', 1)
Taro.navigateTo({ url: '/pages/B/B' })
// B 页面
componentWillMount () {
console.log(Taro.getCurrentInstance().preloadData)
}