我正在使用 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 ()
函数
为什么会发生识别以及如何修复它?
感谢您的帮助:)
最佳答案
您需要将 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){
//...
}
//....
});
关于javascript - React Native - 另一个函数内部无法识别函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52967503/