首页 > 解决方案 > 在 lit-element 中重用 firebase 常量

问题描述

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

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

我尝试过“this.refDoc”,但出现错误:无法读取未定义的属性“集”。在这种情况下,你如何做类似的事情?

谢谢你的帮助!

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)

标签: javascriptfirebasegoogle-cloud-firestorelit-element

解决方案


您在docRef内部进行定义,constructor因此您只能在constructor.

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

  }

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

使用属性的示例。这取决于新的JS 标准

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"
    })
  }
}

使用吸气剂的示例。

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")在需要之前不会执行大量工作,并在组件生命周期的适当阶段对其进行定义。


推荐阅读