2016-11-07 62 views
5

我使用此鏈接作爲我的開始文件製作項目。如何解決錯誤'FB'沒有定義no-undef上create-react-app項目?

https://github.com/facebookincubator/create-react-app

但之後,我試圖通過他們與這個官方的文檔,使Facebook登錄按鈕,如下。

componentDidMount(){ 
    console.log('login mount'); 
    window.fbAsyncInit = function() { 
     FB.init({ 
      appId  : '320866754951228', 
      xfbml  : true, 
      version : 'v2.6' 
     }); 

     FB.getLoginStatus(function(response) { 
      //this.statusChangeCallback(response); 
     }); 

    }; 

    (function(d, s, id){ 
     var 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')); 
} 

所以我得到這個錯誤,當瀏覽器刷新。

Failed to compile. 

Error in ./src/components/user_profile/LoginForm.js 

/Sites/full_stack_production/xxxxx 
    70:13 error 'FB' is not defined no-undef 
    76:13 error 'FB' is not defined no-undef 

✖ 2 problems (2 errors, 0 warnings) 

所以我猜是因爲ESLint導致這個錯誤。 我該如何解決這個問題或爲此FB變量創建例外?

謝謝!

+0

由於FB是一個全球性的,並創建反應的,程序是模塊,你可能有來填補這一點。即使出現錯誤,應用程序是否仍在工作? http://stackoverflow.com/questions/5331165/how-to-workaround-fb-is-not-defined –

回答

13

ESLint不知道變量FB是一個全球性的。您可以通過添加聲明,你作爲一個全球性的引用變量以下到文件的頂部:

/*global FB*/

有關詳細信息,在「規則詳細信息」部分中檢查出官方ESLint文檔:http://eslint.org/docs/rules/no-undef

-1

我可以使用this.FB解決這個問題,而不是僅僅FB

+3

不要使用'this.FB',這是相當混亂。你想'window.FB'。 –

8

如果您使用Create React App,則需要明確地從window中獲取全局變量。
例如:

// It's a global so need to read it from window 
const FB = window.FB; 

但是,如果該庫可作爲NPM包,你可以使用進口:

// It's an npm package so you can import it 
import $ from 'jquery'; 

我希望這有助於!

5

基於什麼@丹阿布拉莫夫在另一個答案評論說:

不要使用FB,使用window.FB

這種方式,你明確地定義,其中變量FB需求從......來。

0

將這個在您的.eslintrc文件,所以你只需要在每一個文件一次,而不是把它定義:

​​
相關問題