javascript - React & firebase-未捕获的 TypeError : Cannot read property 'setState' of undefined

标签 javascript reactjs firebase firebase-realtime-database

在控制台中编译后出现以下错误

Uncaught TypeError: Cannot read property 'setState' of undefined

这是我的代码,你能帮我找出错误吗? 我想将 childData.pic 的数据保存在 x 上,然后读取它 我尝试了 this.x 、 this.state.x 、 x ...,每次我都会收到相同的错误

import React, { Component } from 'react'
import * as firebase from 'firebase'
import './scss/style.scss';
import QuickView from './QuickView';

export default class Dashboard extends Component {
    constructor() {
        super();
        this.state = {
            speed: '', snapshot: undefined, x: ''
        }
    }
    componentDidMount() {
        var w = firebase.auth().currentUser
        var rootRef = firebase.database().ref(`restaus/`).orderByKey();
        rootRef.once("value")
            .then(function (snapshot) {
                snapshot.forEach(function (childSnapshot) {
                    var key = childSnapshot.key;
                    var childData = childSnapshot.val();
                    var x;
                    this.setState({
                        x: childData.pic,
                    })
                });
            });
        this.setState({
            email: w.email,
        })
    }

    render() {
        return (
            <div>
                <h4>your email is {this.state.email}</h4>

                <div className="product">
                    <div className="product-image">
                        <img src={this.x} /*onClick={this.quickView.bind(this, name)}*/ />
                    </div>
                    <h4 className="product-name">{this.state.x}</h4>
                    <p className="product-price">{this.props.x}</p>
                    <div className="product-action">
                        <button type="button" >Add To cart</button>
                    </div>
                </div>
            </div>)
    }
}

最佳答案

请正确格式化您的代码,人们很难理解。问题是您使用 function(snapshot) ,在这种情况下 this 不是指向您的组件,它指向调用它的函数。

您可以使用箭头功能来避免此问题 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

例如:

rootRef.once("value").then((snapshot) => {
   snapshot.forEach((childSnapshot) => {
       ... 
       this.setState(...)
   })
})

关于javascript - React & firebase-未捕获的 TypeError : Cannot read property 'setState' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48440171/

相关文章:

android - Firebase 没有写给预期的 child ,在 Android 的下一个 child 上更新它

javascript - firebase-admin node sdk : Why admin. 数据库既是函数又是属性?

javascript - 单击两次后 jQuery 动画不起作用

javascript - 如果使用 sessionStorage 结束,如何保持动画的状态直到 session 结束?

reactjs - 为什么与 Typescript 函数 react 的解构 props 需要传递一个对象?

reactjs - 如何在 JSX 中插入多行?

javascript - 如何从 React 原生 FormData 对象获取数据

javascript - 如果我在函数内发出警报,则禁用功能正在工作

javascript - 使用 JQuery 的响应式设计

ios - 火力地堡 iOS : createUserWithEmail isn't generating userId (uid)