[英]React & firebase- uncaught TypeError: Cannot read property 'setState' of undefined
I am getting the following error after compiling in the console 在控制台中编译后出现以下错误
Uncaught TypeError: Cannot read property 'setState' of undefined
未捕获的TypeError:无法读取未定义的属性'setState'
this is my code please can u help me to find the mistake ? 这是我的代码,请您能帮我发现错误吗? i wanna save the data of childData.pic on x then i read it on i tried this.x , this.state.x , x ... and every time i get the same error
我想在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>)
}
}
Please format your code properly, it is hard for people to follow. 请正确设置您的代码格式,这很难让人遵循。 The problem is you use
function(snapshot)
, in this case this
not point to your Component, it point to function which call it. 问题是你使用
function(snapshot)
,在这种情况下, this
不是指向您的组件,它指向的函数会调用它。
You can use arrow function to void this issue https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions 您可以使用箭头功能使此问题无效https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions
For example: 例如:
rootRef.once("value").then((snapshot) => {
snapshot.forEach((childSnapshot) => {
...
this.setState(...)
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.