React - 显示 firestore 时间戳

Mel*_*Mel 14 javascript unix-timestamp firebase reactjs google-cloud-firestore

我想弄清楚如何在反应应用程序中显示 firestore 时间戳。

我有一个名为 createdAt 的字段的 firestore 文档。

我试图将它包含在输出列表中(在此处提取相关位,以便您不必通读整个字段列表)。

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()}
Run Code Online (Sandbox Code Playgroud)

唯一不会呈现的属性是日期。

上述每一次尝试都会产生一个错误,说明:

类型错误:无法读取未定义的属性“toDate”

我看过这篇文章这篇文章这篇文章,还有这篇文章和其他类似的文章,这些都表明 toDate() 应该可以工作。但是 - 这个扩展给我抛出了一个错误 - 包括当我尝试 toString 扩展时。

我知道它知道 firestore 中有东西,因为当我尝试 user.createdAt 时,我收到一条错误消息,说它找到了一个包含秒的对象。

以下面的 Waelmas 为例,我尝试将该字段的输出记录为:

this.db.collection('users').doc('HnH5TeCU1lUjeTqAYJ34ycjt78w22').get().then(function(doc) {
  console.log(doc.data().createdAt.toDate());
Run Code Online (Sandbox Code Playgroud)

}

我也尝试将其添加到我的 map 语句中,但收到一条错误消息,指出 user.get 不是函数。

{user.get().then(function(doc) {
                    console.log(doc.data().createdAt.toDate());}
                  )}
Run Code Online (Sandbox Code Playgroud)

它生成与上述相同的错误消息。

在此处输入图片说明

下一次尝试

在尝试找到一种方法在 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();
    };
Run Code Online (Sandbox Code Playgroud)

这可以在数据库中记录日期。

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);
Run Code Online (Sandbox Code Playgroud)

当我尝试回读它时 - 使用:

{item.email}

错误信息如下:

错误:对象作为 React 子对象无效(找到:时间戳(秒 = 1576363035,纳秒 = 52000000))。如果您打算渲染一组子项,请改用数组。在项目中(在 UserIndex.jsx:74)

当我尝试使用这些尝试中的每一个时:

{item.createdAt}
{item.createdAt.toDate()}
{item.createdAt.toDate().toISOString()}
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息:

类型错误:无法读取未定义的属性“toDate”

基于回读记录在其他字段中的同一文档中的条目的能力,我希望这些条目中的任何一个都能产生输出 - 即使它没有按照我想要的方式进行格式化。那不会发生。

下一次尝试

以 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());
Run Code Online (Sandbox Code Playgroud)

} })

这会产生一串语法错误,我找不到解决它们的方法。

下一次尝试

然后我尝试制作一个新表单,看看我是否可以在没有用户表单的身份验证方面进行探索。

我有一个表单,输入为:

this.props.firebase.db.collection("insights").add({
            title: title,
            text: text,
            // createdAt1: new Date(),
            createdAt: this.props.firebase.fieldValue.serverTimestamp()
        })
Run Code Online (Sandbox Code Playgroud)

在前面的表单中, new Date() 尝试在数据库中记录日期,在此示例中, createdAt 和 createdAt1 的两个字段生成相同的数据库条目:

在此处输入图片说明

<div>{item.createdAt.toDate()}</div>
                    <div>{item.createdAt.toDate()}</div>
Run Code Online (Sandbox Code Playgroud)

当我尝试输出日期的值时,第一个会产生一个错误:

对象作为 React 子对象无效(找到:Sun Dec 15 2019 21:33:32 GMT+1100(澳大利亚东部夏令时间))。如果您打算渲染一组子项,请改用数组

第二个生成错误说:

类型错误:无法读取未定义的属性“toDate”

我对下一步尝试的想法感到困惑。

我看到这篇文章表明以下内容可能会做一些有用的事情:

                {item.createdAt1.Date.valueOf()}
Run Code Online (Sandbox Code Playgroud)

它没有。它呈现一个错误,说:

类型错误:无法读取未定义的属性“日期”

这篇文章似乎和我有同样的问题,但没有讨论他们如何设法显示他们存储的日期值。

这篇文章似乎被困在数组错误消息上,但似乎已经弄清楚如何使用 createdAt.toDate() 显示日期

Mic*_*uez 16

经过一些讨论,我们发现 OPs 用户对象中的时间戳可以这样呈现:

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")}
Run Code Online (Sandbox Code Playgroud)

我在一个虚拟的 React 项目中重新创建了您的示例,并收到了与预期相同的错误。

错误:对象作为 React 子对象无效

我能够使用以下方法正确呈现它,这也适用于您:

{new Date(user.createdAt._seconds * 1000).toLocaleDateString("en-US")}
Run Code Online (Sandbox Code Playgroud)

其中,对于我的示例时间戳,呈现为:

12/30/2019


确保您使用的是保存到 Firestore 的时间戳:

createdAt: this.props.firebase.Timestamp.fromDate(new Date())
Run Code Online (Sandbox Code Playgroud)

注意:这是假设您的实例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) 呈现错误的日期


Wae*_*mas 6

当您从 Firestore 获取时间戳时,它们属于以下类型:

在此处输入图片说明

要将其转换为普通时间戳,您可以使用 .toDate() 函数。

例如,对于像下面这样的文档:

在此处输入图片说明

我们可以使用类似的东西:

db.collection('[COLLECTION]').doc('[DOCUMENT]').get().then(function(doc) {
  console.log(doc.data().[FIELD].toDate());
});
Run Code Online (Sandbox Code Playgroud)

输出将类似于:

2019-12-16T16:27:33.031Z
Run Code Online (Sandbox Code Playgroud)

现在要进一步处理该时间戳,您可以将其转换为字符串并使用正则表达式根据您的需要对其进行修改。

例如:(我在这里使用 Node.js)

db.collection('[COLLECTION]').doc('[DOCUMENT]').get().then(function(doc) {
  var stringified = doc.data().[FIELD].toDate().toISOString();
  //console.log(stringified);
  var split1 = stringified.split('T');
  var date = split1[0].replace(/\-/g, ' ');
  console.log(date);
  var time = split1[1].split('.');
  console.log(time[0]);
});
Run Code Online (Sandbox Code Playgroud)

会给你一个这样的输出:

在此处输入图片说明