[英]How do I make the useEffect activate when the "Analyze Weather" button is clicked (react.js)
我希望僅在單擊“分析天氣”按鈕時才發生 useEffect,我該怎么做?
這是我的代碼
const PredictBestPage = () => {
const [latitude , setLatitiude] = useState('')
const [longitude , setLongitude] = useState('')
const [isAnalyzing , setIsAnalyzing] = useState(false)
const API_ENDPOINT = 'https://api.openweathermap.org/data/2.5/onecall?'
const API_KEY = //The Api Key(I cannot show this)
useEffect(() => {
navigator.geolocation.getCurrentPosition((postion) => {
setLatitiude(postion.coords.latitude)
setLongitude(postion.coords.longitude)
})
axios.get(`${API_ENDPOINT}lat=${latitude}&lon=${longitude}&exclude=hourly,daily&appid=${API_KEY}`)
.then((res) => {
console.log(res.data)
})
}, [])
const analyzeWeather = () => {
if(latitude === "" || longitude === "") {
<ErrorPrediction />
}
setIsAnalyzing(true)
}
return (
<>
<Navbar />
{
isAnalyzing
?
<div className = {styles.loader}>
<Loader />
</div>
:
<div className= {styles.predictMainCont}>
<div className= {styles.analyzeBtn} onClick= {analyzeWeather}>
Analyze Weather Conditions
</div>
</div>
}
</>
)
}
export default PredictBestPage
所以基本上我想要它,當我單擊具有功能分析天氣的 onclick 的分析天氣按鈕時,useEffect 應該觸發。 我怎么做? 我是這方面的初學者,謝謝您的幫助。
在 useEffect 中添加您的 useState 變量
useEffect(() => {
navigator.geolocation.getCurrentPosition((postion) => {
setLatitiude(postion.coords.latitude)
setLongitude(postion.coords.longitude)
})
axios.get(`${API_ENDPOINT}lat=${latitude}&lon=${longitude}&exclude=hourly,daily&appid=${API_KEY}`)
.then((res) => {
console.log(res.data)
})
}, [isAnalyzing])
在isAnalyzing
將在您單擊按鈕時運行代碼。
您當前的 useEffect 只會在安裝組件后工作一次。 如果你想通過改變isAnalyzing狀態再次運行它,你必須將它添加到 useEffect 的依賴數組中
useEffect(() => {
// Callback function
}, [dependency array])
所以,你的 useEffect 鈎子必須是:
useEffect(() => {
navigator.geolocation.getCurrentPosition((postion) => {
setLatitiude(postion.coords.latitude)
setLongitude(postion.coords.longitude)
})
axios.get(`${API_ENDPOINT}lat=${latitude}&lon=${longitude}&exclude=hourly,daily&appid=${API_KEY}`)
.then((res) => {
console.log(res.data)
})
}, [isAnalyzing])
但是,有一個重要的事實:您的 useEffect 將被調用一次,無需任何點擊。
如果您不想要這個,您可以簡單地使用常規函數通過 api 調用數據。 這取決於您的業務邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.