reactjs - 将其值存储在反应上下文中时,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}`);
});
}
解决方案
推荐阅读
- excel - 如何使用 PowerShell 将可执行的 excel 文件转换为二进制文件(exe 到 xlsb)?
- r - 根据来自另一个数据帧的两个条件过滤一个数据帧
- import - 如何将外部库添加到处理?
- flutter - 如何在 Flutter 中自定义 Slider 小部件?
- multithreading - 参数化测试以在 MSTEST 中运行并行或单线程
- c++ - 有没有更好的方法来检测我的向量中某个项目的多次出现?
- php - 将发送的发票作为最终发票
- go - Go 结构比较 - reflect.DeepEqual 在地图上失败?
- android - 如何将包含 Firebase 的 android 应用程序从一台计算机转移到另一台计算机
- angular - 延迟加载不会生成任何块Angular 8