2017-03-01 29 views
0

ユーザーが写真を撮った後に関数を呼び出そうとしています。内部のネイティブ呼び出し関数.then非同期関数

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

イメージパスが記録され、エラーは発生しません。

答えて

4

メンバ関数を呼び出すには、thisを使用する必要があります。私は、コールバック内で正しい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); 
    } 


} 

注:ここでは作業例です。

また、このように関数を直接渡すこともできます。

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

あなたは矢印の機能やbindを使用してコンストラクタでを使用して、クラスにdoSomethingをバインドする必要があります。そのためしかし、最後のアプローチは、正しいスコープにdoSomethingを実行しません。 3番目のオプションは、デコレータを使用してBabelを使用してメソッドを自動バインドすることです。

幸運を祈る!

+0

よろしくお願いします。 – user7639007

関連する問題