2017-08-03 36 views
1

我想連接到coincap.io public socket.io API。我已經設置了一切,但不知道在我的組件的哪個位置放置了socket.io代碼。它是否在constructorcomponentWillMount或哪裏?它是socket.io,所以它顯然總是需要打開,所以在一個組件將去哪裏?這是我需要的地方注入到我的組件代碼:將socket.io代碼放在組件中的位置?

this.socket = io.connect('http://socket.coincap.io'); 
this.socket.on('connect', function(tradeMsg) { 
    console.log("It worked"); 
}); 

回答

0

您可以添加socket代碼爲「componentDidMount`。請參閱link

componentDidMount(){ 
    this.socket = io.connect('http://socket.coincap.io'); 
    this.socket.on('connect', function(tradeMsg) { 
     console.log("It worked"); 
    }); 
} 
0

是否在構造函數或componentWillMount去?

檢查這些問題的答案對於這個細節:

Can I call APIs in componentWillMount in React?

Why do the React docs recommend doing AJAX in componentDidMount, not componentWillMount?

凡在我的組件把socket.io代碼?

使用componentDidMount生命週期方法,它會在組件成功掛載後觸發一次,我們應該在其中寫入所有類型的網絡調用。

作爲每DOC

componentDidMount()後的成分是 安裝被立即調用。需要DOM節點的初始化應該放在這裏。如果 需要從遠程端點加載數據,則這是 實例化網絡請求的好地方。在此方法中設置狀態將會觸發重新渲染。

寫這樣的:

componentDidMount(){ 
    this.socket = io.connect('http://socket.coincap.io'); 
    this.socket.on('connect', function(tradeMsg) { 
     console.log("It worked"); 
    }); 
} 
+0

好的謝謝。問題是,它的socket.io不是一個正常的api請求,所以如果它只在componentDidMount()中調用1次,那麼連接仍然是如何打開和監聽? – PurplePanda

相關問題