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

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


}

拍照时出现以下错误:

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在正确的范围内,为此您需要绑定(bind) doSomething到类,使用箭头函数或在构造函数中使用bind .第三种选择是使用装饰器使用 Babel 自动绑定(bind)方法。

祝你好运!

关于.then 异步函数中的 React-Native 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42523110/

相关文章:

android - 类型错误 : null is not an object (evaluating 'RNGestureHandlerModule.default.Direction' )

javascript - 让 JS 函数执行简单的 AJAX true/false 请求并返回结果的最佳方法是什么

javascript - Mongoose 里面的 promise 改变发生得很晚

react-native - ios/android 的 react-native 中的 barcodescanner

ios - iPhone 相机在 react-native 0.55.4 中不起作用?

javascript - 如何在react-navigation中向stackNavigator中的所有屏幕添加通用背景图像?

ios - 警告 : Attempt to present UINavigationController on UIViewController which is already presenting

javascript - 需要帮助尝试在 native react 中刷新我的 token

javascript - 解决错误时对socket.write的 promise (nodejs)

react-native - 使用 react-native-camera,如何访问保存的图片?