我想在 onChange 事件中设置 setInterval,就像大多数情况下在 componentDidMount 上完成的那样。
我有 2 个下拉列表,用于过滤数据然后渲染表格,下拉列表由 onChange 方法控制。最后一个更改方法有一个请求,需要每 X # 秒重新轮询一次,以从服务器获取更新的信息。但是,这些方法不在 cDM 之外,因此我不确定如何像以前一样处理 setInterval
。
cDM() {
//axios call, update state with fetched data
}
onChange1 () {
// uses data from cDM to render the options in a dropdown.
// another axios call based on the selection, fetches data to render more options in subsequent dropdown
}
onChange2 () {
//dropdown 2 use data from onChange1 axios call. After the selection from the dropdown is made, it makes an api call that then renders data to a table.
//Some of this data updates every 5 seconds, so I need to re-poll this service to get updated information from the server.
}
如果所有数据都在 cDM
中,我通常会将 cDM
中的数据请求更改为箭头函数以避免 setState
问题,使用以下内容调用 setInterval
回调内部/外部的函数:
componentDidMount() {
this.interval = setInterval(() => this.getData(), 10000);
this.getData();
}
componentWillUnMount() {
clearInterval(this.interval);
}
getData = () => {
//data requests
}
最佳答案
SetInterval 在重新开始轮询之前不会等待 AJAX 响应。如果出现网络问题,这可能会变得极其错误/内存密集。
我建议您使用 setTimeOut ,并且每次更新时我都会将一段响应数据放入状态中,并在渲染函数内的状态发生变化时启动计时器。这样,您始终可以确保在再次攻击服务器并导致客户端用户界面陷入困境之前返回结果。
关于javascript - React - onChange 事件中的 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53415823/