2017-09-16 21 views
1

得到錯誤時該方法是使用插座反應時socket.io.on方法被調用然後this.state被undedined

componentDidMount(){

var backapi = api.Backend_API(); 
var db = this.state.data; 
console.log("componentDidMount", this.state.data) 
    socket.on('notification', 
    function (notification) { 
    console.log("avi", notification); 
    fetch(backapi + "event/eventname/" + notification.event_id, { 
     method: 'GET', 
    }).then((response) => response.json()) 
     .then((d) => { 
     this.setState({ 
      data: d 
     }) 
     }) 
    fetch(backapi + "user/getUserById/" + notification.created_by, { 
     method: 'GET' 
    }).then((response) => response.json()) 
     .then((data) => { 
     console.log("username socket", data); 
     }) 
    }) 

}

稱爲本地套接字編程

獲取錯誤this.setState未定義使用套接字調用此方法時

+0

請幫助我。 – Ranjeet

回答

1

傳遞給socket.on('notification', ...)處理函數從d不同的情況下this的值是不同的。因此,你必須使用.bind()運營商或只是路過在arrow function這樣明確的背景下的功能綁定:

socket.on('notification', (notification) => {  
    ... 
}); 
+0

非常非常感謝你這麼多@patotoma – Ranjeet

+0

@Ranjeet高興地幫助你,你可以標記我的答案是正確的,如果它回答你的問題,謝謝 – patotoma