![](/img/trans.png)
[英]React - uncaught TypeError: Cannot read property 'setState' of undefined
[英]React & firebase- uncaught TypeError: Cannot read property 'setState' of undefined
在控制台中編譯后出現以下錯誤
未捕獲的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>)
}
}
請正確設置您的代碼格式,這很難讓人遵循。 問題是你使用function(snapshot)
,在這種情況下, this
不是指向您的組件,它指向的函數會調用它。
您可以使用箭頭功能使此問題無效https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions
例如:
rootRef.once("value").then((snapshot) => {
snapshot.forEach((childSnapshot) => {
...
this.setState(...)
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.