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

React Native中使用数据库数据渲染Agenda日历项无显示问题

问题分析与修复方案

核心问题:组件未响应数据更新

你代码里的obj是普通变量,不是React状态变量。当从数据库获取数据并更新obj后,组件不会触发重新渲染,导致Agenda组件始终拿不到最新的日程数据,所以显示为空。

具体修复步骤

1. 改用useState管理日历数据

把存储日程的变量改成React状态,这样数据更新时会自动触发组件重渲染:

const Calendario = () => {
  const dbRef = ref(getDatabase());
  // 用useState初始化空的日程对象
  const [agendaItems, setAgendaItems] = useState({});
  
  // ...后续代码
}

2. 修正数据库数据处理逻辑

  • 先获取合法的Auth实例,替换未定义的app:
const auth = getAuth();
  • 重构数据处理逻辑,避免同日期日程被覆盖,同时直接构建Agenda要求的格式:
const getInDB = () => {
  const auth = getAuth();
  get(child(dbRef, 'users/' + auth.currentUser.uid)).then((snapshot) => {
    const newAgendaItems = {};
    snapshot.forEach(childsnap => {
      // 直接获取子节点的完整数据
      const { date, title, details } = childsnap.val();
      
      // 处理同一天多条日程的情况
      if (!newAgendaItems[date]) {
        newAgendaItems[date] = [];
      }
      newAgendaItems[date].push({ title, details });
    });
    // 更新状态,触发组件重渲染
    setAgendaItems(newAgendaItems);
  }).catch(error => {
    // 新增错误捕获,方便排查权限或路径问题
    console.error('获取日程数据失败:', error);
  });
}

3. 确保日期格式符合要求

react-native-calendars的Agenda要求日期必须是YYYY-MM-DD格式,检查数据库中date字段的格式是否正确。如果格式不符,需要转换:

// 示例:将任意合法日期转换为YYYY-MM-DD格式
const formattedDate = new Date(date).toISOString().split('T')[0];

4. 更新Agenda组件的数据源

把Agenda的items属性改成状态变量:

<Agenda
  items={agendaItems}
  renderEmptyDate={() => <View />}
  renderEmptyData={() => <View />}
  selected={new Date()}
  minDate={null}
  renderItem={renderItem}
  markingType="custom"
/>

额外注意事项

  • 检查用户登录状态:如果auth.currentUser为null,说明用户未登录,需要先处理登录逻辑
  • 验证数据格式:在setAgendaItems前打印newAgendaItems,确保结构为{ '2024-05-20': [{title: 'xxx', details: 'xxx'}] }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 12:33:17