我正在使用Firebase实时存储。我正在尝试从firebase ref.on()函数内部调用函数。
我的代码:
export default class HomeScreen extends React.Component {
constructor(props) {
super(props);
ref.on("value", function (snapshot) {
dosomething(snapshot.val()) //<-- not recognized
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
dosomething(val){
//...
}
//....
});
我正在尝试使dosomething()
函数从ref.on()
函数被调用,但是React无法识别dosomething()
函数
为什么会发生识别以及如何解决?
感谢您的帮助:)
答案 0 :(得分:2)
您需要将function (snapshot) {
更改为(snapshot) => {
现在该回调中的this
是封闭词法上下文的this
值-即构造函数
然后可以使用this.dosomething
-因为dosomething
是this
的属性
export default class HomeScreen extends React.Component {
constructor(props) {
super(props);
ref.on("value", (snapshot) => {
this.dosomething(snapshot.val())
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
dosomething(val){
//...
}
//....
});