在 lit-element 中重用 firebase 常量

Reusing firebase constant in lit-element

在 lit-element 组件中,我正在学习如何写入 Firebase 文档。

我将数据库引用设置为构造函数常量 (docRef)...因为它看起来是个好地方。但是,我无法从方法 writeToDb() 调用它。在下面的代码中,一切正常,但您可以看到我重复了 refDoc (=refDoc2)。

我试过 "this.refDoc" 但我收到错误消息:无法读取未定义的 属性 'set'。在这种情况下,您如何做类似的事情?

感谢您的帮助!

import { LitElement, html } from 'lit-element'
import { store } from '../redux/store'

import { firestore } from '../database/config'
import firebase from 'firebase/app'

import { connect } from 'pwa-helpers'

class ReduxFirebase extends connect(store)(LitElement) {    
  constructor(){
    super()
    const docRef = firestore.doc("samples/sandwichData")
    docRef.set({
      hotDogStatus: "not a sandwich!"
    })

  }

  render() {
    return html`
      <button @click="${this.writeToDb}">Change Status</button>
    `
  }

  writeToDb() {
    const docRef2 = firestore.doc("samples/sandwichData")
    docRef2.set({
      hotDogStatus: "may be a sandwich"
    })
  }
}

customElements.define('redux-firebase', ReduxFirebase)

您正在 constructor 中定义 docRef,因此您只能在 constructor 中访问它。

  constructor(){
    super()
    const docRef = firestore.doc("samples/sandwichData")
    docRef.set({
      hotDogStatus: "not a sandwich!"
    })

  }

如果您希望它在 class 中的任何位置可用,您必须将其定义为实例 属性、getter,或将其设置为 `this.

使用 属性 的示例。这取决于新 JS standard.

class ReduxFirebase extends connect(store)(LitElement) {   
  docRef = firestore.doc("samples/sandwichData")

  constructor(){
    super()
    this.docRef.set({
      hotDogStatus: "not a sandwich!"
    })

  }

  render() {
    return html`
      <button @click="${this.writeToDb}">Change Status</button>
    `
  }

  writeToDb() {
    this.docRef.set({
      hotDogStatus: "may be a sandwich"
    })
  }
}

示例使用 getter。

class ReduxFirebase extends connect(store)(LitElement) {   
  constructor(){
    super()
    this.docRef.set({
      hotDogStatus: "not a sandwich!"
    })

  }

  get docRef() {
    return firestore.doc("samples/sandwichData")
  }

  render() {
    return html`
      <button @click="${this.writeToDb}">Change Status</button>
    `
  }

  writeToDb() {
    this.docRef.set({
      hotDogStatus: "may be a sandwich"
    })
  }
}

this 上的设置示例。

class ReduxFirebase extends connect(store)(LitElement) {   
  constructor(){
    super()
    this.docRef = firestore.doc("samples/sandwichData")
    this.docRef.set({
      hotDogStatus: "not a sandwich!"
    })

  }

  render() {
    return html`
      <button @click="${this.writeToDb}">Change Status</button>
    `
  }

  writeToDb() {
    this.docRef.set({
      hotDogStatus: "may be a sandwich"
    })
  }
}

请注意,您需要确保 firestore.doc("samples/sandwichData") 没有在需要之前执行大量工作,并在 appropriate stage of the component lifecycle.

中定义它

如果要从构造函数对其进行初始化,您可能需要声明 property

 static get properties() {    return { docRef: { type: Object } };  }