javascript并对组件上的异步操作进行反应

时间:2016-03-06 15:29:24

标签: javascript reactjs

我有一个类在ComponentDidMount

中调用了一些异步操作

就像:

componentDidMount(){
// var my_call = new APICall()
Promise.resolve(new APICall()).then(console.log(FB))
}

class APICall{
    constructor(){
        window.fbAsyncInit = () => {
                FB.init({
                    appId      : '254258789655',
                    cookie     : true, 
                    xfbml      : true, 
                    version    : 'v2.5'
                });

            }
        if (typeof(FB) == 'undefined') {
            ((d, s, id) => {
              let js, fjs = d.getElementsByTagName(s)[0];
              if (d.getElementById(id)) return;
              js = d.createElement(s);
              js.id = id;
              js.src = "//connect.facebook.net/en_US/sdk.js";
              fjs.parentNode.insertBefore(js, fjs);
            })(document, 'script', 'facebook-jssdk');
        }
    }
}

export default APICall

这里但我的电话不同步。

如何在调用then课程后调用api的值。

这里给我FB未定义错误。如何首先加载sdk,然后调用FB

谢谢

2 个答案:

答案 0 :(得分:1)

.then会使用引用函数,而您已将console.log的返回结果设为undefined

副作用是调用了console.log,并打印了"hellooww"

您需要提供一个新的执行上下文,也称为回调。

componentDidMount () {
  Promise.resolve(new APICall()).then(function () {
    console.log("hellooww");
  });
}

答案 1 :(得分:0)

当您致电Promise.resolve时,您将返回已解决的承诺,因此then会立即执行。 您可能希望在调用then时执行fbAsyncInit代码,因此您需要构建一些将组件连接到该流的机制。