【问题标题】:How can i use arrow function in Tcpsocket?如何在 Tcpsocket 中使用箭头函数?
【发布时间】:2020-08-18 17:31:10
【问题描述】:
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'未定义)

有没有办法解决这个问题?

【问题讨论】:

    标签: javascript android reactjs react-native tcpsocket


    【解决方案1】:

    我假设这是在类定义中。如果不是,您认为this 指的是什么?

    在定义类成员时不要使用箭头函数,例如handleCreate。这不能正常工作。

    在您的事件处理程序client.on 中,您应该使用箭头函数,因为这将正确捕获this。在您当前的代码中,this 没有引用您期望的对象。实际值取决于事件处理程序的调用方式。

    【讨论】:

      【解决方案2】:

      尝试将 client.on 回调作为箭头函数,而不是普通的函数回调。

      【讨论】: