You need to enable JavaScript to run this app. React Native中使用Moment显示Firestore帖子日期异常问题求助
优惠活动
大模型
产品
解决方案
定价
更多

React Native中使用Moment显示Firestore帖子日期异常问题求助

问题解决方案

问题根因

  • Redux拉取逻辑字段映射错误:当前代码从Firestore文档中提取名为data的字段作为时间戳源,但实际存储时间的字段为dateUpload;同时解析后的时间对象未挂载到timestamp字段,导致item.timestamp为undefined,moment解析undefined时会默认返回当前日期,就是你之前只显示当前日期的原因。
  • 直接使用item.dateUpload报错无效日期,是因为Firestore返回的dateUpload为Timestamp类型对象,无法直接被moment解析,需要先调用.toDate()转为JS原生Date对象。

修复步骤

1. 修正Action.js中的数据解析逻辑

将原代码中字段提取、时间解析的逻辑替换为以下内容:

export function fetchFollowingUsersPosts(uid) {
    return ((dispatch, getState) => {
        firebase.firestore()
            .collection("posts")
            .doc(uid)
            .collection("userPosts")
            .orderBy("creation", "asc")
            .get()
            .then((snapshot) => {
                const uid = snapshot.query.EP.path.segments[1];
                const user = getState().usersState.users.find(el => el.uid === uid);

                const posts = snapshot.docs.map((doc) => {
                    const { dateUpload, ...rest } = doc.data()
                    const id = doc.id;
                    // 解析dateUpload为moment对象,挂载到timestamp字段
                    const timestamp = dateUpload ? moment(dateUpload.toDate()) : null
                  
                    return {
                      ...rest,
                      id,
                      user,
                      timestamp
                    }
                  })

                dispatch({ type: USERS_POSTS_STATE_CHANGE, posts, uid })
            })
    })
}

2. 优化FlatList渲染逻辑(可选,增加异常兼容)

给日期渲染增加空值判断,避免极端情况出现无效日期提示:

postDate={item.timestamp ? item.timestamp.format("ll") : "无日期信息"}

注意事项

  • 所有Firestore返回的Timestamp类型字段,必须先调用.toDate()转为JS Date对象后,才能传入moment进行格式化
  • 上线前可在数据解析阶段增加字段存在性校验,避免字段缺失导致的渲染异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 19:54:04