简体   繁体   中英

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:

    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 .

But the this.setState is inaccessible, I think I need to pass it as a paramete to the socket.on function. But how to do that?

Thanks in advance!

You can use ES6 arrow function in order to access lexical context

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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