在 reactjs 中设置组件 DidMount 上的间隔是一种正确的方法

Setting interval on componentDidMount in reactjs is an correct approach?

本文关键字:一种 方法 设置 reactjs 组件 DidMount      更新时间:2023-09-26

我已经用Reactjs为我的项目创建了聊天应用程序。对于最新更新,我需要每次都点击服务器。 我已经使用了setInterval方法来满足此要求。这种方法是否正确?

例如

componentDidMount:function(){
  setInterval(function(){
    $.ajax({
      url:this.props.url,
      dataType:"JSON",
      type:"GET",
      success:function(data){
        this.setState({data:data});
      }.bind(this)
    });
  }, 1000);
}

是的,这很好,但通常首选递归使用 setTimeout。它可确保在完成超过一秒钟时不会同时处理多个请求。

您可能还想立即运行一次。

最后,您需要清除组件将卸载中的超时。

componentDidMount: function(){
  function tick(){
    $.ajax({
      url: this.props.url,
      dataType: "JSON",
      type: "GET",
      success:function(data){
        this.setState({data: data});
        this.timer = setTimeout(tick, 500);
      }.bind(this)
    });
  };
  tick();
},
componentWillUnmount: function() {
  clearTimeout(this.timer);
}
相关文章: