You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何统计特定页面的用户停留时长并上报数据到API?

实现方案

你使用的是React Navigation顶部标签导航,统计页面停留时长的核心逻辑是监听页面的聚焦(进入)、失焦(离开)事件,计算两个时间点的差值即为停留时长,最后上报到业务API即可,具体实现如下:


步骤1:在Courses组件内添加监听逻辑

直接修改你的Courses组件代码即可,完整示例:

import { useEffect, useRef } from 'react';
import { AppState } from 'react-native';
// 保留你原有其他引入

const Courses = (props) => {
  // 存储进入页面的时间戳
  const enterTimeRef = useRef(null);
  // 存储App前后台状态,处理用户切后台场景
  const appStateRef = useRef(AppState.currentState);

  // 停留时长上报方法
  const reportStayDuration = (duration) => {
    // 替换为你实际的上报接口地址
    fetch('你的业务上报API地址', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        pathway_id: props.route.params?.pathway_id,
        page_name: 'Course',
        stay_duration: Math.round(duration / 1000), // 单位为秒,需要毫秒的话直接用duration即可
        report_time: Date.now()
      })
    })
  }

  useEffect(() => {
    // 监听页面聚焦:用户进入Course页面时触发
    const focusListener = props.navigation.addListener('focus', () => {
      enterTimeRef.current = Date.now();
    });

    // 监听页面失焦:用户切到其他标签页/跳转到其他页面时触发
    const blurListener = props.navigation.addListener('blur', () => {
      if (!enterTimeRef.current) return;
      const stayDuration = Date.now() - enterTimeRef.current;
      // 可自定义最小上报阈值,比如停留超过1秒再上报,过滤误触、快速滑动标签的无效数据
      if (stayDuration >= 1000) {
        reportStayDuration(stayDuration);
      }
      enterTimeRef.current = null;
    });

    // 监听App前后台切换,避免用户直接切后台/关应用漏统计
    const appStateListener = AppState.addEventListener('change', nextAppState => {
      // App切后台时,如果当前在Course页面则上报时长
      if (appStateRef.current === 'active' && nextAppState.match(/inactive|background/)) {
        if (enterTimeRef.current) {
          const stayDuration = Date.now() - enterTimeRef.current;
          if (stayDuration >= 1000) {
            reportStayDuration(stayDuration);
          }
          enterTimeRef.current = null;
        }
      } 
      // App回到前台时,如果当前在Course页面则重新记录进入时间
      else if (appStateRef.current.match(/inactive|background/) && nextAppState === 'active') {
        if (props.navigation.isFocused()) {
          enterTimeRef.current = Date.now();
        }
      }
      appStateRef.current = nextAppState;
    });

    // 组件卸载时清除监听,补报未上报的时长
    return () => {
      focusListener();
      blurListener();
      appStateListener.remove();
      if (enterTimeRef.current) {
        const stayDuration = Date.now() - enterTimeRef.current;
        if (stayDuration >= 1000) {
          reportStayDuration(stayDuration);
        }
      }
    }
  }, [props.navigation, props.route.params?.pathway_id]);

  // 保留你原有Courses组件的业务逻辑和渲染内容
  return (
    // 原有页面代码
  )
}

export default Courses;

注意事项

  • 如果你用的是React Navigation 4及更早版本,把事件监听的写法替换为onWillFocus、onWillBlur对应的绑定逻辑即可
  • 上报阈值、时长单位可根据业务需求自行调整

内容的提问来源于stack exchange,提问作者Harsh Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 06:36:05