首页 > 解决方案 > 为什么 react-native-gifted-chat 不能从 firebase 时间戳正确显示时间?

问题描述

我在我的应用程序中使用了react-native-gifted-chat来添加聊天功能。目前我能够正确发送和接收来自 firebase 的消息。但是,问题是react-native-gifted-chat总是显示 12:00 AM 的消息发送时间。这是因为它无法将 firebase 时间戳转换为时间。谁能帮我解决一下?

这是我使用GiftedChat组件的方式:

<GiftedChat
  messages={this.props.messages}
  renderUsernameOnMessage={true}
  onSend={messages => this.onSend(messages)}
  alwaysShowSend={true}
  textInputStyle={styles.composer}
  minComposerHeight={40}
  minInputToolbarHeight={60}
  user={{
    _id: this.props.account ?.user ?.uid,
    name: this.props.account ?.data ?.fullName,
    avatar: this.props.account ?.data ?.avatar
  }}
/>

以下是我用于在 firestore 中保存消息的代码:

export const sendMessage = (message, groupId) => {
  return async () => {
    await firestore().collection('groupMessages').doc(groupId).collection('messages').doc(message._id).set(message).catch((e) => {
      throw {message: e.message.replace(`[${e.code}] `, '')}
    });
  }
}

在上面的代码中是有天赋的聊天消息,message其中包含属性:_id、、text和。createdAtuser

以下是消息在 firebase 中的存储方式:

Firebase 消息结构

当我显示消息时:

信息

标签: javascriptfirebasereact-nativereact-native-firebasereact-native-gifted-chat

解决方案


最后用临时解决方案完成。renderTime我通过按道具将时间渲染为自定义来解决它。

<GiftedChat
  ...
  renderTime={(props) => (
    <View style={props.containerStyle}>
      <CText size={10} style={{marginHorizontal: 10, marginBottom: 5}} bold color={props.position === "left" ? 'gray' : 'white'}>
        {`${props.currentMessage.createdAt.toDate().toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })}`}
      </CText>
    </View>
  )}
  ...
  ...
/>

我已转换createdAt为日期,然后以hh:mm AM/PM格式获取它。

注意:这只是临时解决方案,如果您在本地存储消息并显示消息,则可能无法正常工作,因为 GiftedChat 生成的消息字段createdAt是纯 javascript 日期对象,没有任何toDate()功能,因此您可能会收到此类错误。

Uncaught TypeError: (intermediate value).toDate 不是 :1:12 的函数


推荐阅读