[英]Set Time Interval for Fetching Data inside React Life Cycle Methods
我正在構建一個反應應用程序,用於在 rest-api 中顯示數據。為了做到這一點,我使用了 componentDidMount 方法並成功獲取數據而沒有任何混淆。 我的代碼片段如下所示。
componentDidMount() {
fetch('http://localhost:5000/sensors')
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
sensors: json,
})
console.log(this.state.sensors);
});
}
我的要求是每 40 秒獲取一次數據並更新表而不刷新 web 頁面。 誰能幫我解決這個問題?
根據我的要求,因為我需要以 40 秒的時間間隔加載表數據,我可以在componentWillMount()方法中使用 Javascript 內置方法setInterval() 。 如問題所示,可以從componentDidMount()完成render()之后的初始數據加載。
下面是我以 40 秒的時間間隔獲取數據的代碼。
componentWillMount(){
setInterval(() => {
fetch('http://localhost:5000/sensors')
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
sensors: json,
})
console.log(this.state.sensors);
});
}, 40000);
}
據我所知,我認為如果不重新渲染組件(沒有變異狀態)就不可能更新 state,因為 react 使用淺渲染,它基本上檢查以前和當前的 state,如果它們不匹配,則重新渲染,如果你問我,在沒有 memory 泄漏和一堆錯誤的情況下做到這一點,你可以
a)使用單獨的組件來獲取目的並顯示結果(如您所說的表格),以便只有組件重新渲染(並使用 redux 或 contextAPI。無論您想要什么),您也可以在用戶渲染時使用 componentWillUnmount (將被棄用)另一個頁面來清除間隔。 (或者您可以使用鈎子並返回 function 以清除間隔)
useEffect(()=>{
const interval = setInterval(()=>{
//fetch here
},40000);
return () => {
cleanInterval(interval)
}
},[tableData /*this is supposed to be the state value of the data you fetch*/])
b) 突變 state。 這不是一個好主意(它會導致更多的錯誤和錯誤)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.