在控制台中编译后出现以下错误
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/