【问题标题】:React Native - Function is not recognized inside Another FunctionReact Native - 在另一个函数中无法识别函数
【发布时间】:2018-10-24 11:12:31
【问题描述】:

我正在使用 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() 函数

为什么会发生这种情况,我该如何解决?

感谢您的帮助:)

【问题讨论】:

    标签: javascript firebase react-native firebase-storage


    【解决方案1】:

    您需要将function (snapshot) { 更改为(snapshot) =&gt; {

    现在该回调中的 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){
        //...
      }
    
      //....
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-19
      • 2021-11-20
      相关资源
      最近更新 更多