.then 异步函数中的 React-Native 调用函数

React-Native call function inside .then async function

我正在尝试在用户拍照后调用一个函数。我尝试通过以下方式这样做:

export default class LA extends Component {
    constructor(props) {
      super(props);
      this.doSomething = this.doSomething.bind(this);
    }


    takePicture() {
      this.camera.capture()
      .then(function(data) {
        doSomething(data.path); //THIS CAUSES THE RUNTIME ERROR
      })
     .catch(err => console.error("error: " + err));
    }

    doSomething(imgPath) {
      console.log(imgPath);
    }


}

拍照时出现以下错误:

error: Reference Error: doSomething is not defined

但是,如果我将 takePicture() 替换为:

takePicture() {
  this.camera.capture()
  .then(function(data) {
    console.log(data.path);
  })
 .catch(err => console.error("error: " + err));
}

图片路径已记录,未出现错误。

您需要使用this才能调用成员函数。这是一个工作示例:

export default class LA extends Component {
  constructor(props) {
    super(props);
    this.doSomething = this.doSomething.bind(this);
  }


  takePicture() {
    this.camera.capture()
    .then((data) => {
      this.doSomething(data.path);
    })
   .catch(err => console.error("error: " + err));
  }

  doSomething(imgPath) {
    console.log(imgPath);
  }


}

请注意,我在回调中使用了箭头函数来引用正确的 this

或者你也可以直接传函数,像这样

  takePicture() {
    this.camera.capture()
      .then(this.doSomething)
      .catch(err => console.error("error: " + err));
  }

但是,最后一种方法不会 运行 doSomething 在正确的范围内,为此您需要使用箭头将 doSomething 绑定到 class函数或在构造函数中使用 bind。第三种选择是使用装饰器自动绑定使用 Babel 的方法。

祝你好运!

export default class LA extends Component {

  ...


  takePicture1() {
    this.camera.capture()
    .then((data) => {
      this.doSomething(data.path);   // CORRECT
      // keyword `this` represents instance of class LA
    })
   .catch(err => console.error("error: " + err));
  }


  takePicture2() {
    this.camera.capture()
    .then(function (data) {
      this.doSomething(data.path); // WRONG
      // function defines `this` as the global object 
      // (because it's where the function is executed)
    })
   .catch(err => console.error("error: " + err));
  }

  doSomething(imgPath) {
    console.log(imgPath);
  }
}