gpt4 book ai didi

reactjs - 使用 ES6 语法将数据从 Firebase 3 读取到 React 组件中

转载 作者:行者123 更新时间:2023-12-02 15:18:38 26 4
gpt4 key购买 nike

我一直在努力解决一个简单的用例:在我的 React 网络应用程序上从 Firebase 数据库读取一个数字,即注册用户数,并在页面加载时显示它。

有旧版本 React 和 Firebase 的文档,但看起来这个用例应该可以通过新方式实现。

Screenshot of my Firebase Database.

import React from 'react'
import {Badge} from 'react-bootstrap'
var firebase = require('firebase')
var config = {
apiKey: "MyKey", // redacted key
authDomain: "dnavid-c48b6.firebaseapp.com",
databaseURL: "https://dnavid-c48b6.firebaseio.com",
storageBucket: "dnavid-c48b6.appspot.com",
};
var firebaseApp = firebase.initializeApp(config);
var UCRef = firebaseApp.database().ref("numberofusers")
class UserCount extends React.Component{
constructor(props){
super(props)
this.state = {usercount: '3'}
}
componentDidMount() {
// this.setState({usercount:4}) // This actually works and displays "4"
var uc = UCRef.on('value',function(snapshot){return(snapshot.val())})
debugger;
this.setState({usercount:uc}) // This does not work
}
render(){
return (
<Badge>
{this.state.usercount}
</Badge>
)
}
}
export default UserCount;

在 Chrome 调试器中(注意“调试器”命令)我进入了控制台:

> uc
<. function(snapshot) {
return snapshot.val();
}

> uc()
Uncaught TypeError: Cannot read property 'val' of undefined(…)

从中我可以推断,由于快照未定义,事件没有被触发。但这听起来不合逻辑:

  1. componentDidMount 已被评估(因为组件已呈现并且执行在调试器停止检查时到达它)
  2. Firebase 文档声称事件已触发,请参阅下文“附加监听器时触发一次此方法”。

Value events You can use the value event to read a static snapshot of the contents at a given path, as they existed at the time of the event. This method is triggered once when the listener is attached and again every time the data, including children, changes. The event callback is passed a snapshot containing all data at that location, including child data. If there is no data, the snapshot returned is null.

那么,监听器是不是没有被附加?怎么回事?

最佳答案

你需要这样做:

componentDidMount() {
UCRef.on('value', snapshot => {
this.setState({usercount: snapshot.val()});
});
}

UCRef.on('value', func) 不会返回值。您可以在回调中获取它

关于reactjs - 使用 ES6 语法将数据从 Firebase 3 读取到 React 组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38877539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com