2016-04-19 36 views
0

我正在構建一個React應用程序,並且我注意到我正在使用一個函數兩次以上。所以我決定將它提取出來並且創建一個新的類。它看起來像這樣:加載異步請求的其他類

export default class Fetcher { 
    constructor(url, callback) { 
    this.url = url; 
    this.callback = callback; 
    } 

    getData() { 
    const url = '/wp-json/wp/v2/' + this.url; 
    const req = new XMLHttpRequest(); 

    req.open('get', url, true); 
    req.onreadystatechange =() => { 
     if(req.readyState === 4) { 
     if(req.status === 200) { 
      this.callback(); 
      return req.responseText; 
     } else { 
      throw new Error(); 
     } 
     } 
    } 
    req.send(); 
    } 
} 

,我使用它是這樣的:

import Fetcher from '../Tools/XML'; 
    fetchPost() { 
    const data = new Fetcher('posts?slug='+this.props.params.slug, this.renderPost); 
    console.log(data.getData()); 
    } 

我的問題是,console.log回報undefined。我明白髮生這種情況是因爲請求是異步的,並且在查詢完成之前渲染完成。

我的問題是,我該如何克服這個問題?

回答

1

您需要使用回調,因爲異步工作時不能有直接返回值。

getData()方法,改變這一行:

this.callback(); 

向該:

this.callback(req.responseText); 

然後把的console.log在回調函數:

renderPost(responseText) { 
    console.log(responseText); 
} 
+0

很好用!謝謝! –

+0

@TomekBuszewski乾杯,不熟悉react.js,但熟悉由於node.js和AngularJS引起的異步JavaScript。 :) –

0

XMLHttpRequest API使用相同的命名構造函數按照MDN:進行異步調用。

在你的場景中,你正在使用這個api,但是api不能直接返回任何數據給調用者,因爲getData()沒有向它的調用者返回任何東西,這是一種異步方法。 因爲,你有callback(),它用於使用

this.callback(req.responseText); 

因此,一旦該方法完成通過異步調用的結果返回給調用者,回調將被傳遞的responseText作爲參數。爲了處理這個改變,回調的方法簽名接受這個參數爲:

renderPost (responseText) { 
    // Use the response now 
    console.log(responseText); 
}