javascript - 在 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)
解决方案
您在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")
在需要之前不会执行大量工作,并在组件生命周期的适当阶段对其进行定义。
推荐阅读
- c# - 发送电子邮件 WebAPI
- git - 开启gitlab的二次验证后如何使用git命令
- html - 如何使用 XSLT 1.0 检查元素的前面子字符串?
- mongodb - 使用 .jks 文件从 shell 连接到 mongo
- angular - 用于 mat-selection-list 的角材料“disableRipple”在移动设备中不起作用
- ffmpeg - 这是在转码视频吗?
- uml - UML 活动图:在输出上带有保护条件的分叉
- bash - Bash 脚本冲突
- ios - 如何创建如下图所示的渐变阴影(绿色按钮上方):
- java - 从 ListFragment android 启动另一个 Fragment