[英]How can we stop repeated calls in componentDidUpdate() lifecycle of a class based component, like we do in useEffect hook?
useEffect(()=>{ fetch(`${BASE_URL}/requested_url`) .then(response => response.json()) .then(json => setData(json)) }, []);
當我使用基於 class 的組件時,我不得不使用 state boolean 來指定何時開始獲取和停止......我仍然很奇怪我想知道是否可以停止工作在 componentDidUpdate() 生命周期方法中也重復調用請求。
componentDidUpdate() { if (this.state.show2) { return fetch(`${BASE_URL}/requested_url`) .then(response => response.json()) .then(json => setState({ data: json, show2: false })) } return; }
我知道這不是從生命周期進行請求調用的正確方法。 也不要因此評判我......所以,請告訴我是否有人可以幫助我正確地做到這一點,或者這樣做是否合法......
useEffect
中的第二個屬性是一個依賴數組。 基本上,效果中使用的任何外部變量都需要放在那里,因為 function 只會在它們改變值時運行。
useEffect(()=>{
if (show2)
fetch(`${BASE_URL}/requested_url`)
.then(response => response.json())
.then(json => setData(json))
}, [show2]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.