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

Expo v49 React Native页面数据库数据不实时更新问题求助

解决方案

核心问题分析

  • 首页原有的useEffect仅在value状态变化时触发,但value仅在组件首次挂载时从AsyncStorage读取一次,返回首页时value无变化,导致数据库查询不会重新执行。
  • useFocusEffect未生效大概率是用法错误,比如未正确包裹异步逻辑或依赖处理不当。
  • router.replace("/home")不会触发页面重新挂载,因此原useEffect无法重新执行。

具体修复步骤

1. 重构首页数据加载逻辑,改用useFocusEffect

首先导入所需依赖:

import { useFocusEffect } from '@react-navigation/native';
import { useCallback } from 'react';

然后替换原有的useEffect逻辑,确保每次页面聚焦时重新拉取数据:

const [value, setValue] = useState(null);
const [meters, setMeters] = useState([]);
const { getItem } = useAsyncStorage("@id");

// 封装数据查询逻辑,用useCallback保证函数引用稳定
const fetchMeters = useCallback(async () => {
  // 读取当前用户ID
  const userId = await getItem();
  setValue(userId);

  // 用户ID存在时查询数据库
  if (userId) {
    db.transaction((tx) => {
      // 改用参数化查询,避免SQL注入风险
      tx.executeSql(
        `SELECT * FROM meters WHERE meters.userID = ?;`,
        [userId],
        (_, { rows: { _array } }) => {
          setMeters(_array);
          console.log("最新仪表数据:", _array);
        },
        (_, error) => {
          console.error("数据库查询失败:", error);
          return false;
        }
      );
    });
  }
}, [getItem]);

// 使用useFocusEffect监听页面聚焦,每次聚焦时执行数据查询
useFocusEffect(
  useCallback(() => {
    fetchMeters();
  }, [fetchMeters])
);

2. 确保添加记录后再跳转首页

在Add Meters页面,必须等待数据库插入操作完成后再执行跳转,避免数据未写入就返回:

// 示例添加记录函数
const addMeter = async () => {
  try {
    // 等待数据库插入完成
    await new Promise((resolve, reject) => {
      db.transaction((tx) => {
        tx.executeSql(
          `INSERT INTO meters (userID, meterName, ...) VALUES (?, ?, ...);`,
          [userId, meterName, ...其他参数],
          () => resolve(),
          (_, error) => reject(error)
        );
      });
    });
    // 插入成功后返回首页
    router.replace("/home");
  } catch (error) {
    console.error("添加仪表失败:", error);
    // 这里可以添加用户错误提示,比如Alert.alert("错误", "添加失败,请重试")
  }
};

3. 检查数据库实例有效性

确保db实例是全局初始化的,或者在组件中正确导入,避免useFocusEffect执行时db未定义的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 07:48:12