2016-04-19 34 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); 
}