javascript - 直接从 firebase rtdb 获取数据时出现 TypeError : Cannot read property 'setState' of null,

标签 javascript reactjs firebase firebase-realtime-database

为什么我的状态没有使用我直接从 direbase 获取的数据进行更新 enter image description here

我在控制台中获取数据的位置

enter image description here

我在这里做错了什么, 错误在这里 enter image description here

最佳答案

更改此:

const db = firebase.database().ref('users/trainers/'+uid).on('value', function(snapshot){
   // here this refers to the firebase callback scope 
    this.setState({
        .........
        .........
    })
}))

进入此:

const db = firebase.database().ref('users/trainers/'+uid).on('value', (snapshot) =>{
   // here this refers to the firebase callback scope 
    this.setState({
        .........
        .........
    })
}))

使用箭头函数:

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.

关于javascript - 直接从 firebase rtdb 获取数据时出现 TypeError : Cannot read property 'setState' of null,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59943344/

相关文章:

javascript - React 应用程序中登录页面的路由保护

reactjs - react : If you set state in a request animation frame will react schedule rendering on the animation frame?

java - Firebase,类映射器 : no setter/field found for 'UserTwo' on class 'myclass'

javascript - Firebase 云函数 - 函数返回未定义、预期的 Promise 或值

javascript - 为什么我的 innerHTML 方法无法在我的联系表单中列出内容?

javascript - elementLocated 与 findElements 的结果不一致

javascript - 单击列表项时加载 div

javascript - 预加载样式表而不在页面上执行它

javascript - 尝试使用 Google API 时遇到 cors 问题

android - 如何将对象列表写入 firebase?