【问题标题】:React: Firebase Listener Not Working反应:Firebase 监听器不工作
【发布时间】:2016-09-04 22:40:39
【问题描述】:

我在 YouTube 上关注这个截屏视频,但在我的一生中,我似乎无法让我的数据库与我的 React 应用程序对话。

componentDidMount() 函数正在运行,但 .on() 侦听器函数似乎没有触发。

我的代码如下所示:

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import * as firebase from 'firebase';

var config = {
  // config from firebase db lives here
};

firebase.initializeApp(config);

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import * as firebase from 'firebase';

class App extends Component {

  constructor() {
    super();
    this.state = {
      speed: 10
    }
  }

  componentDidMount() {
    const rootRef = firebase.database().ref().child('react');
    const speedRef = rootRef.child('speed');

    speedRef.on('value', snap => {
      this.setState({
        speed: snap.val()
      });
    });
  }

  render() {
    return (
      <div className="App">
        <h1>{this.state.speed}</h1>
      </div>
    );
  }
}

export default App;

FWIW,我的数据库看起来像这样:

我在控制台中得到零错误,完全没有想法。我做错了什么。

感谢任何帮助。提前致谢!

【问题讨论】:

  • 解决了!这与我的 Firebase READ 规则有关。有人可以关闭这个吗?
  • 正确的做法是回答您的问题,然后接受该答案。这也是我的问题,你的问题/答案也让我得到了正确的答案。
  • @awwester 添加了答案。

标签: javascript reactjs firebase firebase-realtime-database


【解决方案1】:

解决了!这个问题与我的 Firebase READ 规则有关。如果遇到类似问题,请检查数据库规则。

【讨论】:

    猜你喜欢
    • 2013-07-12
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    相关资源
    最近更新 更多