我已经使用 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 通常是首选。如果需要一秒钟以上的时间才能完成,它可以确保您不会同时处理多个请求。
您可能还想立即运行一次。
最后需要清除componentWillUnmount中的超时
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);
}
关于javascript - 在 reactjs 中设置 componentDidMount 间隔是一种正确的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36170009/