【问题标题】:Stop React from rendering code that opens websockets停止 React 渲染打开 websocket 的代码
【发布时间】:2018-08-05 21:08:20
【问题描述】:

我在 render() 中有这段代码,它打开一个 websocket 并连接到一个 Rest 服务。

return (
      <div className="App">  

        <SockJsClient 
          url = 'http://localhost:8610/refresh/'
          topics={['/topic/notification']} 
          onConnect={console.log("Connection established!")} 
          onDisconnect={console.log("Disconnected!")}
          onMessage={(msg) => this.update()}
          debug= {true}
        />

一切正常 - 这种方法的唯一问题是,当重新呈现 UI 时,应用程序会关闭 websocket 并再次重新打开它。没有任何中断,应用程序只是恢复,没有任何反应。

这个操作非常消耗资源吗?有没有办法告诉 react 不要重新渲染那部分代码?我应该担心吗?

this.update() 在我的state 中重新设置一个数组。

我知道shouldComponentUpdate() 是我需要的,但是我必须创建一个新组件来进行重新渲染,对吧?我很困惑。

谢谢!

编辑:这也有效(@zavjs 的解决方案更干净)

componentDidMount(){

  var self = this; // use self to reference this

  var socket = new SockJS("http://192.168.1.139:8610/refresh");
  var stompClient = Stomp.over(socket);
  stompClient.connect({}, function(frame,) {
    console.log('connected: ' + frame);
    stompClient.subscribe('/topic/notification', function(notification) {
      self.update();  // here
    })
  }, function(err) {
    console.log('err', err);
  });

还有here's 更多关于此的信息!

【问题讨论】:

    标签: reactjs websocket sockjs


    【解决方案1】:

    是的,我会创建一个中间组件来包裹您的 SocketJSClient,并在您有意进行重新渲染时设置 shouldComponentUpdate 条件(也许当像 url 这样的 Socket 配置发生更改并且您需要传递它时)下,例如)。

    class PreventUpdate extends React.Component {
      shouldComponentUpdate = (nextProps) => {
        //set true if a Socket connection config has changed
        //or something that needs to trigger a re-render in the 
        //child component 
        if(this.nextProps.shouldPreventUpdate) {
          return false;
        }
      };
    
      render() {
        this.props.children;
      }
    }
    

    现在你可以这样做了:

    <PreventUpdate
      shouldPreventUpdate={someDynamicCondition}>
      <SocketJSClient />
    <PreventUpdate/>
    

    有了这个,你可以传入一个任意标志来防止更新组件及其所有子组件。我希望它适合你

    【讨论】:

    • 太棒了,这是有道理的!我摆弄了一会儿,发现我可以在调用stompClient.subscribe('http.....') {..} 之前执行此var self = this; 并将其引用为self.update(),它也可以工作!
    猜你喜欢
    • 2023-01-30
    • 1970-01-01
    • 2021-04-06
    • 2018-02-22
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 2013-08-24
    • 2014-07-09
    相关资源
    最近更新 更多