2017-09-16 19 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