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

时间:2017-03-01 04:19:12

标签: react-native promise react-native-camera

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

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);
    }


}

拍照时出现以下错误:

  

错误:引用错误:未定义doSomething

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

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

记录图像路径,不会发生错误。

2 个答案:

答案 0 :(得分:4)

您需要使用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绑定到类,或者使用{{1}在构造函数中绑定bind }。第三种选择是使用装饰器使用Babel自动绑定方法。

祝你好运!

答案 1 :(得分:0)

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);
  }
}
相关问题