子组件通过Web套接字检索数据的React最佳实践是什么?

时间:2019-12-13 09:34:03

标签: reactjs websocket

我对React还是有些陌生,并且正在尝试设置一个从WebSocket连接检索其自身数据的子组件。此Web套接字连接在父ComponentDidMount中建立,并通过道具socket传递给子组件。

这个问题是,我必须定义getDerivedStateFromProps才能仅在第一次定义this.props.socket时(在父级中异步建立连接)来检索子级组件中的数据。一种替代方法是使用setInterval轮询要在this.props.socket中定义的componentDidMount

这两种方法都不是理想的。有没有办法让子组件等待父组件完全建立连接?按照最佳实践完成此操作的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

将WebSocket对象放入prop中有点奇怪,因为prop主要用于传输数据。

一种实现方法是将所有websocket部分保留在父级中,然后让子级通过状态和回调使用它。

class Parent extends React.Component {
  constructor() {
    this.state = {
      websocketData: null
    }

    this.websocket = null
    /* ... */
  }

  componentDidMount() {
    let wsScheme = window.location.protocol === 'https:' ? 'wss' : 'ws'
    this.webSocket = new WebSocket(sScheme + '://' + window.location.host + url)

    webSocket.onmessage = (event) => {
      const data = /* get received data from event */
      this.setState({websocketData:data})
    }

    webSocket.onClose = () => console.warn('Websocket closed unexpectedly'
  }

  componentWillUnmount() {
    if (this.websocket) {
      this.websocket.close()
    }
  }

  sendToWebsocket(data) {
    if (this.websocket) {
      webSocket.send(data)
    }
  }


  render() {
    return (
      <ChildComponent websocketData={this.state.websocketData} sendToWebsocket={this.sendToWebsocket}/>
    )
  }
}