[英]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']);
});
}
我想將服務器中的數據動態保存到 this.state 中。 但是,我在控制台中收到消息 => TypeError:this.handleCreate is not a function。 (在 'this.handleCreate(strData)' 中,'this.handleCreate' 未定義)
有沒有辦法解決這個問題?
我假設這是在 class 定義中。 如果不是,您認為this
是指什么?
在定義 class 成員時不要使用箭頭函數,例如handleCreate
。 那不能正常工作。
在您的事件處理程序client.on
,您應該使用箭頭 function 因為這將正確捕獲this
。 在您當前的代碼中this
沒有引用您期望的 object。 實際值取決於調用事件處理程序的方式。
嘗試client.on
回調為箭頭 function 而不是正常的 function 回調。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.