首页 > 解决方案 > 将其值存储在反应上下文中时,Websocket无法在反应中工作

问题描述

当用户单击登录按钮时,我想打开 websocket 连接。我在做什么,在app.js中我正在创建 websocket 并将其保存在反应上下文中。然后在login.js中,从反应上下文中获取套接字值,当用户单击登录按钮时,尝试打开连接,但它不起作用。如果我尝试在 app.js 中打开连接而不将其保存在上下文中,那么代码工作正常。

应用程序.js:-

import SocketContext from './shared/socketContext.js';

const socket = new WebSocket("wss://javascript.info/article/websocket/demo/hello");


class App extends React.Component{
  render(){
    return(
      <>
      <Router>
        <Switch>
          <SocketContext.Provider value={socket}> // passing the value of socket in react context
          <Route path='/login' component={Login}/>
          <Route path='/dashboard' component={Dashboard}/>
          <Redirect to='/login' />
          </SocketContext.Provider>
        </Switch>
      </Router>
      </>
    )
  }
}

登录.js:-

   componentDidMount(){
        this.inputRef.current.focus();
        console.log(this.props.userDetails);
        console.log(this.props.socket); 
//getting the socket value on console when component did mount.
    }

        componentDidUpdate(){
        if(this.props.userDetails !== ''){
            console.log(`user name is ${this.props.userDetails}`)
            this.openSocketConnection() //opening the connection once userdetails have some value.
        }
    }

    openSocketConnection(){
        const a = this.props.socket ;
        a.addEventListener('open',()=>{
            console.log('Connection has established')
            // this.props.history.push('/dashboard');
        })
        this.props.socket.addEventListener('message',(event)=>{
            alert(`[message] Data received from server: ${event.data}`);
          });
    }

标签: reactjswebsocketreact-context

解决方案


推荐阅读