2017-03-01 44 views
0

我想在用戶拍照後調用一個函數。我嘗試通過以下方式來完成:裏面的React-Native調用函數。異步函數

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才能調用成員函數。這裏有一個工作示例:

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到類,使用箭頭功能或構造使用bind。第三個選項是使用裝飾器使用Babel自動綁定該方法。

祝你好運!

+0

非常感謝您的幫助! – user7639007