2016-12-07 40 views
0

這是我的工作代碼:如何觸發反應,用套接字重新渲染UI?

import socket from 'components/io/socket'; 
import store from 'components/store'; 
// globally available socket connection 
class ChatBox extends React.Component { 
    componentDidMount(){ 
    socket.on("message", this.props.addChat.bind(this)); 
    // this.props.addChat is reduxer actions. 
    } 
} 

不過,我很擔心這樣的代碼,很可能引入內存泄漏,因爲舊的客艙部分將仍然由插座refered。

我試圖把它變成:

import socket from 'components/io/socket'; 
import store from 'components/store'; 
socket.on("message", store.dispatch(addChat({...})) 

class ChatBox extends React.Component { 
    render(){ ... } 
} 

但是第二碼犯規觸發HTML被重新描繪,即使當我使用斷點,電話,store.getState()插座收到消息後的結果變化。

回答

0

您可以覆蓋componentWillUnmmount退訂監聽器和從而使插槽釋放到客艙你所擔心的參考。

但是,由於每次撥打bind都會創建一個全新的實例,因此您不會在componentWillUnmmount處具有偵聽器引用。爲了解決這個問題,在構造函數中綁定方法。

constructor(props) { 
    super(props); 

    this.addChat = this.props.addChat.bind(this); 
} 

componentDidMount() { 
    socket.on("message", this.addChat); 
} 

componentWillUnmount() { 
    socket.off("message", this.addChat); // or whatever it is called 
} 

不管怎麼說,我覺得奇怪,我有綁定到組件的外來法(props從外部傳遞)。通常你訂閱的組件本身的方法,所以你可以肯定正在發生的事情 - 特別是因爲該方法可以自由改變實例的任何屬性,如狀態或事件的addChat結合。所以,你可能想要回顧一下。也許轉換爲高階組件?

相關問題