简体   繁体   English

如何在 Tcpsocket 中使用箭头 function?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM