简体   繁体   English

在 React 中,如何将“this.state”作为参数传递给“socket.on”回调 function?

[英]In React, how to pass “this.state” as parameter to “socket.on” callback function?

I am using Socket.io and React, and I have a function:我正在使用 Socket.io 和 React,我有一个 function:

    this.state.socket.on("newMentions", function (data) {
      this.setState({         // Cannot read "this" here.
        newMentions: data
      })
    })

The socket is store in state of this class component, and I want to define its on event, which should set some new date to the state by using this.setState . socket存储在此state组件的 state 中,我想定义它的on事件,它应该使用 this.setState 为this.setState设置一些新日期。

But the this.setState is inaccessible, I think I need to pass it as a paramete to the socket.on function.但是this.setState是不可访问的,我想我需要将它作为参数传递给socket.on function。 But how to do that?但是怎么做呢?

Thanks in advance!提前致谢!

You can use ES6 arrow function in order to access lexical context您可以使用 ES6 箭头 function 来访问词汇上下文

 this.state.socket.on("newMentions",(data)=> {
      this.setState({        
        newMentions: data
      })
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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