首页 文章

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

提问于
浏览
0

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

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

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

1 回答

  • 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(...)
       })
    })
    

相关问题