uni-app 使用reLaunch打开index页面时,index的onLoad方法中调用uni.startPullDownRefresh(),onPullDownRefresh监听出现调用多次

uni-app 使用reLaunch打开index页面时,index的onLoad方法中调用uni.startPullDownRefresh(),onPullDownRefresh监听出现调用多次

开发环境 版本号 项目创建方式
Mac 11.5.2 (20G95) HBuilderX

示例代码:

<template> <view class="content"> <image class="logo" src="/static/logo.png"></image> <view class="text-area"> <text class="title">{{title}}</text> </view> </view> </template> <script> export default { data() { return { title: 'Hello' } }, onLoad() { uni.startPullDownRefresh() }, onShow() { // uni.startPullDownRefresh() }, onPullDownRefresh() { console.log('刷新了'); uni.stopPullDownRefresh() }, methods: { } } </script> <style> .content { display: flex; flex-direction: column; align-items: center; justify-content: center; } .logo { height: 200rpx; width: 200rpx; margin-top: 200rpx; margin-left: auto; margin-right: auto; margin-bottom: 50rpx; } .text-area { display: flex; justify-content: center; } .title { font-size: 36rpx; color: #8f8f94; } </style>


<template>  
    <view>  
        <view style="width: 200rpx;height: 200rpx;background-color: #007AFF;" @click="test">按钮1</view>  
        <view style="width: 200rpx;height: 200rpx;background-color: #ff7AFF;" @click="test">按钮2</view>  

    </view>  
</template>  

<script>  
    export default {  
        data() {  
            return {  

            }  
        },  
        methods: {  
            test(){  
                uni.reLaunch({  
                    url:"../index/index"  
                })  
                // uni.switchTab({  
                //  url:"../index/index"  
                // })  
            }  
        }  
    }  
</script>  

<style>  

</style>  
1 回复

uni-app 中使用 uni.reLaunch 打开 index 页面时,如果在 onLoad 方法中调用 uni.startPullDownRefresh(),可能会导致 onPullDownRefresh 监听方法被多次调用。这是因为 uni.reLaunch 会关闭所有页面,然后重新打开目标页面,可能会导致页面生命周期钩子被多次触发。

解决方案

  1. 使用 setTimeout 延迟调用 uni.startPullDownRefresh: 你可以在 onLoad 方法中使用 setTimeout 延迟调用 uni.startPullDownRefresh(),以确保页面完全加载后再触发下拉刷新。

    onLoad() {
      setTimeout(() => {
        uni.startPullDownRefresh();
      }, 300); // 延迟 300ms
    }
  2. onShow 中调用 uni.startPullDownRefresh: 你可以将 uni.startPullDownRefresh() 的调用移到 onShow 生命周期钩子中,以确保页面显示后再触发下拉刷新。

    onShow() {
      uni.startPullDownRefresh();
    }
  3. 使用标志位防止多次调用: 你可以使用一个标志位来确保 uni.startPullDownRefresh() 只被调用一次。

    let isRefreshCalled = false;
    
    onLoad() {
      if (!isRefreshCalled) {
        uni.startPullDownRefresh();
        isRefreshCalled = true;
      }
    }
  4. 检查页面栈: 你可以通过检查页面栈来确保 uni.startPullDownRefresh() 只在你期望的页面中调用。

    onLoad() {
      const pages = getCurrentPages();
      if (pages.length === 1 && pages[0].route === 'pages/index/index') {
        uni.startPullDownRefresh();
      }
    }
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!