[英]How can i use arrow function in Tcpsocket?
handleCreate = (data) => {
const { wifi } = this.state;
this.setState({
wifi: wifi.concat({ id: this.id++, ...data })
})
}
componentDidMount(){
this.handleCreate();
}
render(){
const client = TcpSocket.createConnection({
port: 80,
host: '192.168.4.100',
tls: false,
interface: 'wifi',
localAddress: '192.168.4.101',
}, () => {
client.write('APPSETTING WIFI START');
});
client.on('data', function(data) {
//console.log('message was received', data);
var strData="";
let dataLen = data.length;
for(var i=0; i<dataLen; i++){
strData+=String.fromCharCode(data[i]);
//console.log('message is', String.fromCharCode(data[i]));
}
console.log('message is', strData);
this.handleCreate(strData)
//client.end();
//console.log('message is', data['data']);
});
} }
I want to save data from server into this.state dynaimycally.我想将服务器中的数据动态保存到 this.state 中。 But, I got message in console => TypeError: this.handleCreate is not a function.
但是,我在控制台中收到消息 => TypeError:this.handleCreate is not a function。 (In 'this.handleCreate(strData)', 'this.handleCreate' is undefined)
(在 'this.handleCreate(strData)' 中,'this.handleCreate' 未定义)
Is there any way to solve this problem?有没有办法解决这个问题?
I assume this is within a class definition.我假设这是在 class 定义中。 If not what do you think
this
refers to?如果不是,您认为
this
是指什么?
Don't use arrow functions when defining class members, such as handleCreate
.在定义 class 成员时不要使用箭头函数,例如
handleCreate
。 That does not work correctly.那不能正常工作。
In your event handler client.on
you should use an arrow function because this will correctly capture this
.在您的事件处理程序
client.on
,您应该使用箭头 function 因为这将正确捕获this
。 In your current code this
does not reference the object you expect.在您当前的代码中
this
没有引用您期望的 object。 The actual value depends on how your event handler is called.实际值取决于调用事件处理程序的方式。
try client.on
callback as arrow function instead a normal function callback.尝试
client.on
回调为箭头 function 而不是正常的 function 回调。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.