javascript - 为什么 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
和。createdAt
user
以下是消息在 firebase 中的存储方式:
当我显示消息时:
解决方案
最后用临时解决方案完成。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 的函数
推荐阅读
- c++ - 指向多维数组的第 n 个元素的指针
- javascript - 如何查找对象的哪个属性包含特定值?
- html - 检测并处理 CSS 中的“分页符”条件?
- r - 更改 ggplot 中模型的顺序(dotwhisker)
- c# - 使用 C#,是否可以在不定义大量类型的情况下查询 YAML?
- surface - pygame,如何在屏幕上显示角色3秒然后消失
- regex - 使用 Python 正则表达式提取电子邮件域
- powershell - 为什么 JENKINS 不在 Powershell 区域中使用环境变量?
- reactjs - 在反应导航上动态添加更多屏幕到 stackNavigator
- sqlalchemy - SQLAlchemy 布尔值与布尔值