重用火元素常量

时间:2019-03-10 18:05:48

标签: javascript firebase google-cloud-firestore 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)

2 个答案:

答案 0 :(得分:1)

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

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

  }

如果希望它在类中的任何位置都可用,则必须将其定义为实例属性,获取器,或在“ 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"
    })
  }
}

使用吸气剂的示例。

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中进行定义。

答案 1 :(得分:0)

如果要从构造函数中初始化property,则可能需要声明它。

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