我试图弄清楚如何在React应用程序中显示Firestore时间戳。
我有一个Firestore文档,其中包含一个名为createdAt的字段。
我正在尝试将其包含在输出列表中(在此处提取相关位,以便您不必通读整个字段列表)。
componentDidMount() {
this.setState({ loading: true });
this.unsubscribe = this.props.firebase
.users()
.onSnapshot(snapshot => {
let users = [];
snapshot.forEach(doc =>
users.push({ ...doc.data(), uid: doc.id }),
);
this.setState({
users,
loading: false,
});
});
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const { users, loading } = this.state;
return (
<div>
{loading && <div>Loading ...</div>}
{users.map(user => (
<Paragraph key={user.uid}>
<key={user.uid}>
{user.email}
{user.name}
{user.createdAt.toDate()}
{user.createdAt.toDate}
{user.createdAt.toDate()).toDateString()}
唯一无法呈现的属性是日期。
上面的每种尝试都会产生一个错误,指出:
我已经看到this post,this post和this post以及this post和其他类似的东西,这表明toDate()应该可以工作。但是-该扩展名对我抛出错误-包括当我尝试toString扩展名时。
我知道它知道Firestore中有什么东西,因为当我尝试user.createdAt时,我收到一条错误消息,说它找到了一个包含秒数的对象。
以下面的Waelmas为例,我尝试将字段的输出记录为:
this.db.collection('users').doc('HnH5TeCU1lUjeTqAYJ34ycjt78w22').get().then(function(doc) {
console.log(doc.data().createdAt.toDate());
}
我还尝试将其添加到我的map语句中,但收到一条错误消息,指出user.get不是函数。
{user.get().then(function(doc) {
console.log(doc.data().createdAt.toDate());}
)}
它生成与上述相同的错误消息。
下一个尝试
试图找到一种在Firestore中记录日期的方法而发生的一件奇怪的事情是,当我以一种形式更改提交处理程序以使用此公式时,可以让我回读它:
handleCreate = (event) => {
const { form } = this.formRef.props;
form.validateFields((err, values) => {
if (err) {
return;
};
const payload = {
name: values.name,
// createdAt: this.fieldValue.Timestamp()
// createdAt: this.props.firebase.fieldValue.serverTimestamp()
}
console.log("formvalues", payload);
// console.log(_firebase.fieldValue.serverTimestamp());
this.props.firebase
.doCreateUserWithEmailAndPassword(values.email, values.password)
.then(authUser => {
return this.props.firebase.user(authUser.user.uid).set(
{
name: values.name,
email: values.email,
createdAt: new Date()
// .toISOString()
// createdAt: this.props.firebase.fieldValue.serverTimestamp()
},
{ merge: true },
);
// console.log(this.props.firebase.fieldValue.serverTimestamp())
})
.then(() => {
return this.props.firebase.doSendEmailVerification();
})
// .then(() => {message.success("Success") })
.then(() => {
this.setState({ ...initialValues });
this.props.history.push(ROUTES.DASHBOARD);
})
});
event.preventDefault();
};
这可以在数据库中记录日期。
firestore条目的形式如下:
我正在尝试在此组件中显示日期:
class UserList extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
users: [],
};
}
componentDidMount() {
this.setState({ loading: true });
this.unsubscribe = this.props.firebase
.users()
.onSnapshot(snapshot => {
let users = [];
snapshot.forEach(doc =>
users.push({ ...doc.data(), uid: doc.id }),
);
this.setState({
users,
loading: false,
});
});
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const { users, loading } = this.state;
return (
<div>
{loading && <div>Loading ...</div>}
<List
itemLayout="horizontal"
dataSource={users}
renderItem={item => (
<List.Item key={item.uid}>
<List.Item.Meta
title={item.name}
description={item.organisation}
/>
{item.email}
{item.createdAt}
{item.createdAt.toDate()}
{item.createdAt.toDate().toISOString()}
</List.Item>
// )
)}
/>
</div>
);
}
}
export default withFirebase(UserList);
当我尝试将其读回时,请使用:
{item.email}
错误消息显示为:
当我尝试使用以下每种尝试时:
{item.createdAt}
{item.createdAt.toDate()}
{item.createdAt.toDate().toISOString()}
我收到一条错误消息:
基于能够读回其他字段中同一文档中记录的条目的能力,我希望其中任何一个都可以产生输出-即使它不是按照我想要的方式格式化的。那不会发生。
下一个尝试
以Waelmas的示例为例,我尝试按照说明进行操作,但是第一步没有得到相同的答复。在Walemas基于.toDate()扩展名获取输出的地方,我收到一条错误消息,指出toDate()不是函数。
与Firebase文档一致,我尝试过:
const docRef = this.props.firebase.db.collection("users").doc("HnH5TeCU1lUjeTqAYJ34ycjt78w22");
docRef.get().then(function(docRef) {
if (doc.exists) {
console.log("Document createdAt:", docRef.createdAt.toDate());
}
})
这会产生语法错误字符串,而我找不到解决方法。
下一个尝试
然后,我尝试制作一个新表单,看看是否可以在没有用户表单的身份验证方面进行探索。
我有一个输入为的表格:
this.props.firebase.db.collection("insights").add({
title: title,
text: text,
// createdAt1: new Date(),
createdAt: this.props.firebase.fieldValue.serverTimestamp()
})
在前一种形式中,新的Date()尝试在数据库中记录日期,在此示例中,createdAt和createdAt1的两个字段都生成相同的数据库条目:
<div>{item.createdAt.toDate()}</div>
<div>{item.createdAt.toDate()}</div>
当我尝试输出日期的值时,第一个生成一个错误,指出:
第二个生成错误说:
我对接下来要尝试的方法有想法。
我看到this post暗示以下内容可能会做一些有用的事情:
{item.createdAt1.Date.valueOf()}
没有。它将显示一个错误,指出:
这个post似乎和我有同样的麻烦,但是没有涉及他们如何显示存储的日期值。
这个post似乎卡在了数组错误消息上,但是似乎已经弄清楚了如何使用createdAt.toDate()显示日期。
最佳答案
经过一些讨论,我们发现OP用户对象中的时间戳可以这样渲染:
render() {
const { users, loading } = this.state;
return (
<div>
{loading && <div>Loading ...</div>}
{users.map(user => (
<Paragraph key={user.uid}>
<key={user.uid}>
{user.email}
{user.name}
{new Date(user.createdAt.seconds * 1000).toLocaleDateString("en-US")}
我在一个虚拟的React项目中重新创建了您的示例,并收到与预期相同的错误。
我可以使用以下方法正确呈现此效果,该方法也适用于您:
{new Date(user.createdAt._seconds * 1000).toLocaleDateString("en-US")}
对于我的示例时间戳,其表示为:
确保使用的时间戳记已保存为Firestore:
createdAt: this.props.firebase.Timestamp.fromDate(new Date())
注意:这是假设您的
firebase.firestore()
实例位于this.props.firebase
。在其他示例中,您使用this.props.firebase,但是这些方法看起来像您自己创建的帮助器方法。提取此值后,它将是一个具有两个属性的对象
_seconds
和_nanoseconds
。确保包括下划线。如果您使用
createdAt.seconds
,则无法使用,它必须是createdAt._seconds
。我尝试过的其他方法:
user.createdAt.toDate()
抛出toDate() is not a function
。user.createdAt
引发Error: Objects are not valid as a React child
new Date(user.createdAt._nanoseconds)
呈现错误的日期关于javascript - react -显示Firestore时间戳,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59277859/