Я настраиваю простое приложение погоды, используя React и Hooks. Однако я обнаружил, что приложение продолжает загружать API. Как я могу это остановить?
function WeatherInfo (props) { const [wind,setWind] = useState(undefined); const [precipitation,setPrecipitation] = useState(undefined); const [humidity,setHumidity] = useState(undefined); const [pressure,setPressure] = useState(undefined); if (props.city) { useEffect(() => { fetch(`https://api.openweathermap.org/data/2.5/weather?q=${props.city}&units=metric&APPID=af081727ae6d5c4cbe2cd266b726e632`).then(results => {return results.json();} ).then(data => setWind(data.wind.speed)) }) useEffect(() => { fetch(`https://api.worldweatheronline.com/premium/v1/weather.ashx?key=a5bf94fc16c84928acb114156182311&q=${props.city}&num_of_days=1&tp=24&format=json`).then(results => {return results.json();} ).then(data => setPrecipitation(data.data.weather[0].hourly[0].chanceofrain)) }) useEffect(() => { fetch(`https://api.openweathermap.org/data/2.5/weather?q=${props.city}&units=metric&APPID=af081727ae6d5c4cbe2cd266b726e632`).then(results => {return results.json();} ).then(data => setPressure(data.main.pressure)) }) useEffect(() => { fetch(`https://api.openweathermap.org/data/2.5/weather?q=${props.city}&units=metric&APPID=af081727ae6d5c4cbe2cd266b726e632`).then(results => {return results.json();} ).then(data => setHumidity(data.main.humidity)) }) } return ( <div> {props.city && <div> <p>Wind of {props.city} is {wind}</p> <p>Chance of rain of {props.city} is {precipitation}%</p> <p>Humidity of {props.city} is {humidity}</p> <p>Pressure of {props.city} is {pressure}</p> </div> } </div> ) } export default WeatherInfo;
Ожидаемый результат: Функция только выбирает API один раз
вы можете использовать setInterval, чтобы ограничить частоту выполнения кода, например
setInterval(function(){ if (props.city) { useEffect(() => { fetch(`https://api.openweathermap.org/data/2.5/weather?q=${props.city}&units=metric&APPID=af081727ae6d5c4cbe2cd266b726e632`).then(results => {return results.json();} ).then(data => setWind(data.wind.speed)) }) useEffect(() => { fetch(`https://api.worldweatheronline.com/premium/v1/weather.ashx?key=a5bf94fc16c84928acb114156182311&q=${props.city}&num_of_days=1&tp=24&format=json`).then(results => {return results.json();} ).then(data => setPrecipitation(data.data.weather[0].hourly[0].chanceofrain)) }) useEffect(() => { fetch(`https://api.openweathermap.org/data/2.5/weather?q=${props.city}&units=metric&APPID=af081727ae6d5c4cbe2cd266b726e632`).then(results => {return results.json();} ).then(data => setPressure(data.main.pressure)) }) useEffect(() => { fetch(`https://api.openweathermap.org/data/2.5/weather?q=${props.city}&units=metric&APPID=af081727ae6d5c4cbe2cd266b726e632`).then(results => {return results.json();} ).then(data => setHumidity(data.main.humidity)) })}}, 10000);
, затем просто установите время, как часто вы хотите его проверять
По умолчанию хук useEffect запускается при каждом рендеринге. Если вы этого не хотите, вы можете указать второй необязательный аргумент, см. https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects.
useEffect
В вашем конкретном случае: вы, вероятно, хотите выполнить эффект только при смене города, поэтому: useEffect(/* callbacks as before */, [props.city]).
useEffect(/* callbacks as before */, [props.city])
Кроме того, вы должны вызывать хуки только на верхнем уровне (т.е. не в ifs): https://reactjs.org/docs/hooks-overview.html#%EF%B8%8F-rules-of-hooks. Вы можете переместить ветвь if в обратные вызовы useEffect