【问题标题】:Where to put socket.io code in a component?将 socket.io 代码放在组件中的什么位置?
【发布时间】:2017-08-03 07:03:26
【问题描述】:

我想连接到coincap.io 公共socket.io API。我已经设置好了所有东西,但不知道在我的组件中放置socket.io 代码的位置。它是在constructor 或componentWillMount 还是在哪里?它是socket.io,所以它显然总是需要打开,那么它会在组件中的哪个位置?这是我需要在组件中注入的代码:

this.socket = io.connect('http://socket.coincap.io');
this.socket.on('connect', function(tradeMsg) {
    console.log("It worked");
});

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    是放在构造函数还是componentWillMount中?

    查看这些答案以了解有关此问题的详细信息:

    Can I call APIs in componentWillMount in React?

    Why do the React docs recommend doing AJAX in componentDidMount, not componentWillMount?

    在我的组件中哪里放置 socket.io 代码?

    使用componentDidMount生命周期方法,它只会在组件挂载成功后触发一次,我们应该在其中编写各种网络调用。

    根据DOC:

    componentDidMount() 在组件被调用后立即调用 安装。需要 DOM 节点的初始化应该放在这里。如果你 需要从远程端点加载数据,这是一个很好的地方 实例化网络请求。在此方法中设置状态将 触发重新渲染。

    这样写:

    componentDidMount(){
        this.socket = io.connect('http://socket.coincap.io');
        this.socket.on('connect', function(tradeMsg) {
            console.log("It worked");
        });
    }
    

    【讨论】:

    • 好的,谢谢。问题是它的 socket.io 不是一个普通的 api 请求,所以如果它在 componentDidMount() 中只被调用 1 次,那么连接如何仍然打开并监听?
    • 我所做的是创建一个单独的文件来连接和请求套接字。我从登录中调用 connect 方法,其中我使用与常规快速端点相同的身份验证过程,即中间件。我将 JWT 存储在两个 cookie 中,这些 cookie 与我的 api 和 socket 调用一起发送。我服务器上的中间件重建 JWT 并在 express 和 socket.io 的情况下使用它进行身份验证。这允许您在 componentDidMount 中调用上述连接方法,如果套接字为空,则重新连接,cookie 在刷新后仍然存在。
    【解决方案2】:

    您可以将socket 代码添加到“componentDidMount”中。参考link

    componentDidMount(){
        this.socket = io.connect('http://socket.coincap.io');
        this.socket.on('connect', function(tradeMsg) {
          console.log("It worked");
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-26
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 2018-01-22
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多