【问题标题】:Setting a created timestamp in Firestore with React使用 React 在 Firestore 中设置创建的时间戳
【发布时间】:2019-09-09 05:40:15
【问题描述】:

我正在将文档添加到表单的 Firestore 集合 (inboxItems) onSubmit

onCreateInboxItem = event => {
  this.props.firebase.inboxItems().add({
    name: this.state.newInboxItemName,
    created: '', // I need a timestamp field here
  })
  this.setState({ name: '' });
  event.preventDefault();
}

如何让created 字段成为时间戳字段,并将当前时间戳作为值?它需要在用户和时区之间保持一致。

我看到firebase docs 中提到了firebase.firestore.FieldValue.serverTimestamp(),但此时尚未设置字段值。我想避免更新字段的额外操作。

【问题讨论】:

  • 我不清楚为什么不能使用 FieldValue.serverTimestamp()。您只需在调用 add() 时将其用作字段的值。
  • "this.props.firebase.firestore.FieldValue.serverTimestamp()" 似乎不起作用。也许我在这里引用了一些错误的东西,但我认为 FieldValue 只有在字段已经设置时才能访问。

标签: reactjs firebase google-cloud-firestore


【解决方案1】:

你可以这样做:

created: new Date(),

或:

created: firebase.firestore.Timestamp.fromDate(new Date()),

或者,您可以使用云功能,如 here 所述,尽管这可能有点矫枉过正。

【讨论】:

  • 是的,但这不是根据本地机器时间创建时间戳吗?我需要确保它在用户和时区之间保持一致。
  • 我相信这仍然会创建一个本地时间戳,该函数似乎只是将您的本地时间戳转换为 Firebase 时间戳。我在文档中看到了诸如“firebase.firestore.FieldValue.serverTimestamp()”之类的内容,但此时尚未设置字段值。
  • 您应该能够在您正在谈论的示例中使用set() 代替update()
【解决方案2】:

由于我使用 firebase 身份验证,因此我通过上下文 API 使用根 App 组件初始化 firebase。我设法通过在我的 Firebase 设置文件中添加一个助手来解决它:

class Firebase {
  constructor() {
    app.initializeApp(config);

    /* Helper */

    this.fieldValue = app.firestore.FieldValue;

    /* Firebase API's */

    this.db = app.firestore();
  }
}

然后:

this.props.firebase.inboxItems().add({
  created: this.props.firebase.fieldValue.serverTimestamp(),
  name: this.state.newInboxItemName,
})

【讨论】:

  • 通常您只需将app 提供给您的整个应用程序,这样您就不必从中挑选出您需要的部分。大多数 JavaScript 只是假设它是一个名为 firebase 的全局变量。
  • 我使用 React Context API,因此我可以在根组件级别提供一个 firebase 实例(需要身份验证、更高效且不易出错)。这意味着 firebase 作为 props 传递给子组件,这就是需要 helper 的原因。
  • @DougStevenson robinwieruch.de/complete-firebase-authentication-react-tutorial 上有一个非常简洁的例子,我相信这是在 react 中使用 firebase 的更可靠的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-01
  • 2020-04-04
  • 2018-10-22
  • 2011-05-31
  • 1970-01-01
  • 2019-06-21
  • 1970-01-01
相关资源
最近更新 更多