时,setstate是不确定的。
使用套接字调用此方法时获取错误
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);
})
})
}
获取错误此方法使用套接字
传递给socket.on('notification', ...)
处理程序的函数从不同上下文执行,因此this
的值不同。因此,您必须使用.bind()操作员或仅通过这样的箭头函数将上下文绑定到函数:
socket.on('notification', (notification) => {
...
});