反应& firebase- uncaught TypeError:无法读取属性' setState'未定义的

时间:2018-01-25 10:01:58

标签: javascript reactjs firebase firebase-realtime-database

在控制台中编译后,我收到以下错误

  

未捕获的TypeError:无法读取属性' setState'未定义的

这是我的代码,请你帮我找错? 我想在x上保存childData.pic的数据然后我读它 我试过这个.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>)
    }
}

1 个答案:

答案 0 :(得分:2)

请正确格式化您的代码,人们很难关注。问题是您使用function(snapshot),在这种情况下this没有指向您的Component,它指向调用它的函数。

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

例如:

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