在 React js 中重新连接 WebSocket
Reconnect WebSocket in react js
Web 套接字服务器在特定时间重新启动,我希望我的 React 前端应用程序每次重新启动连接。
这段代码运行良好,但只有一次。我希望它在每次连接丢失时重新连接:
_connectSocketStreams(streams) {
streams = streams.join('/');
let connection = btoa(streams);
const { BASE_WSS_PATH } = wssPath;
this[connection] = new WebSocket(`${BASE_WSS_PATH}/!ticker`);
this[connection].onmessage = evt => {
let ticker = this._getTickerBySymbol(JSON.parse(evt.data))
this.props.dispatch({
type: 'UPDATE_MARKET_PAIRS',
data: ticker
})
!this.props.active_market.market && this._UsdtActive('USDT')
this.setState({
isLoaded: true
})
}
this[connection].onerror = evt => {
console.error(evt);
}
this[connection].onclose = evt => {
this[connection] = null;
console.log('closed')
this[connection] = new WebSocket(`${BASE_WSS_PATH}/!ticker`);
this[connection].onmessage = evt => {
let ticker = this._getTickerBySymbol(JSON.parse(evt.data))
this.props.dispatch({
type: 'UPDATE_MARKET_PAIRS',
data: ticker
})
!this.props.active_market.market && this._handleTabClick('USDT')
this.setState({
isLoaded: true
})
}
};
}
我在 class 组件构造函数中使用它
这将获取数据流并将其显示在 table.
中
我试图将 _connectSocketStreams
传递给 .onclose
事件:
// setTimeout(this._connectSocketStreams(streams), 1000)
但是我得到了这个错误:
TypeError: streams.join is not a function
即使我认为这是正确的方法。我很困惑!
这使它如我所愿地工作:
this[connection].onclose = evt => {
this[connection] = null;
console.log('closed')
setTimeout(this._connectSocketStreams(['!ticker@arr']), 1000)};
Web 套接字服务器在特定时间重新启动,我希望我的 React 前端应用程序每次重新启动连接。
这段代码运行良好,但只有一次。我希望它在每次连接丢失时重新连接:
_connectSocketStreams(streams) {
streams = streams.join('/');
let connection = btoa(streams);
const { BASE_WSS_PATH } = wssPath;
this[connection] = new WebSocket(`${BASE_WSS_PATH}/!ticker`);
this[connection].onmessage = evt => {
let ticker = this._getTickerBySymbol(JSON.parse(evt.data))
this.props.dispatch({
type: 'UPDATE_MARKET_PAIRS',
data: ticker
})
!this.props.active_market.market && this._UsdtActive('USDT')
this.setState({
isLoaded: true
})
}
this[connection].onerror = evt => {
console.error(evt);
}
this[connection].onclose = evt => {
this[connection] = null;
console.log('closed')
this[connection] = new WebSocket(`${BASE_WSS_PATH}/!ticker`);
this[connection].onmessage = evt => {
let ticker = this._getTickerBySymbol(JSON.parse(evt.data))
this.props.dispatch({
type: 'UPDATE_MARKET_PAIRS',
data: ticker
})
!this.props.active_market.market && this._handleTabClick('USDT')
this.setState({
isLoaded: true
})
}
}; }
我在 class 组件构造函数中使用它 这将获取数据流并将其显示在 table.
中我试图将 _connectSocketStreams
传递给 .onclose
事件:
// setTimeout(this._connectSocketStreams(streams), 1000)
但是我得到了这个错误:
TypeError: streams.join is not a function
即使我认为这是正确的方法。我很困惑!
这使它如我所愿地工作:
this[connection].onclose = evt => {
this[connection] = null;
console.log('closed')
setTimeout(this._connectSocketStreams(['!ticker@arr']), 1000)};