javascript - React Native - 另一个函数内部无法识别函数

标签 javascript firebase react-native firebase-storage

我正在使用 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 - 因为 dosomethingthis

的属性
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/

相关文章:

PHP/javascript 实时聊天使用过多带宽

java - 当用户不喜欢评论时,该用户的所有通知都会从数据库中删除,而不是仅删除该特定通知

ios - 使用 Parse 用户进行 Firebase 身份验证

react-native - 无法使用 react-native-fs lib 在 react-native 中运行 Jest 单元测试

javascript - React-Native 动态图像源?

javascript - 如何区分javascript对象中的url和字符串

javascript - 如果数组包含特定值,则返回该值的完整 'content'

javascript - 'fetch' 方法是否提供与 'FileReader' 相同的功能?

firebase - Flutter/Firestore- 'List<dynamic>'类型不是 'Widget'类型的子类型

javascript - 在严格模式下函数表达式中定义的变量的范围是什么?