React + Firebase数据库组件DidMount和快照不起作用

时间:2018-11-03 03:26:04

标签: javascript reactjs firebase firebase-realtime-database

我正在尝试触发.on('value'),以便我可以检索数据,但某些功能无法正常工作。 “安装”日志很好,但是“测试”却不好。有人可以解释一下我可能造成的误解吗?另外,我想更新状态,如注释掉的代码所示。

谢谢您的帮助!

    import React, { Component } from 'react'
import './Creature.css'
import Emblem from '../../../img/emblem_macabre.png'
import Macabre from '../../../img/macabre.jpg'
import * as firebase from 'firebase';

class Creature extends Component {

  constructor() {
    super()
    this.state = {
      name: '',
      cultId: ''
    }
  }

  componentDidMount() {
    console.log('mounted')
    const creatureCards = firebase.database().ref().child('creatureCards')
    console.log(creatureCards)
    creatureCards.on('value', snap => {
      console.log('test')
    })

      // var name = snap.child('name').getValue()
      // var cultId = snap.child('cultId').getValue()

      // this.setState({
      //   name: name,
      //   cultId: cultId
      // })
    }

  render() {
    return(
      <div className="creatureCard">
        <span className="creatureName">{this.state.name}</span>
        <span className="creatureArt"><img src={Macabre} alt=""/></span>
        <ul className="creatureAttributes">
          <li className="creatureAttribute">R</li>
          <li className="creatureAttribute">D</li>
          <li className="creatureAttribute">I</li>
          <li className="creatureAttribute">H</li>
        </ul>
        <span className="creatureDescription">
          <p>Card descriptions and abilities. This section defines the card and its roll in the game.</p>
        </span>
        <div className="emblem">
          <img src={Emblem} alt=""/>
        </div>
      </div>
    )
  }
}

export default Creature

1 个答案:

答案 0 :(得分:0)

问题在于,有时我切换到了Firestore,但仍在对数据库进行调用。