我知道useEffect中的[]会导致函数运行一次。我尝试的其他任何操作都会创建一个无限循环。get请求只运行了一次,但在刷新页面后就不会再运行了。如有任何帮助将不胜感激。谢谢!
import React from 'react';
import { useState, useEffect } from 'react';
import axios from 'axios';
const Weather = () =>{
const [weather, setWeather] = useState();
const [lat, setLat] = useState([]);
const [long, setLong] = useState([]);
const [url, setUrl] = useState(``);
const getLocation = () => {
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition((position) =>{
let la = position.coords.latitude;
let lon = position.coords.longitude;
setLat(la)
setLong(lon)
setUrl(`http://api.weatherapi.com/v1/current.json?key=6e6263afb84f44279f731543222510&q=${lat},${long}`)
})
}
}
const getWeater = async () =>{
await axios.get(url).then((response) =>{
const weatherData = response.data;
setWeather(weatherData);
console.log(weather)
})
}
useEffect(() =>{
getLocation();
getWeater();
},[])
}
export default Weather;
2条答案
按热度按时间n3h0vuf21#
包含单独的useEffect和
url
作为触发API调用的副作用ijnw1ujt2#
我们可以使用setInterval在几秒或几分钟后调用这些函数,在setInterval内只调用一个函数来调用这两个函数,我附上了代码
的示例