繁体   English   中英

使用 UseEffect 时如何阻止 React App 在刷新时中断

[英]How to stop a React App breaking on refreshing when using UseEffect

    import {useState, useEffect } from 'react'
import axios from 'axios'

const Singlecountry = ({searchedCountries, setWeather, weather}) => {
  const weatherName = searchedCountries[0].capital
  const iconname = () => {
    if (weather === undefined) {
      return null
    }
     weather.map(w => w.weather[0].icon)
  }
  console.log(iconname)
  useEffect(() => {
 

    axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${weatherName}&appid=${process.env.REACT_APP_API_KEY}`)
      .then(response => {
        const apiResponse = response.data;
        console.log(apiResponse)
        console.log(`Current temperature in ${apiResponse.name} is ${apiResponse.main.temp - 273.15}℃`);
    setWeather([apiResponse])
      }).catch(error => {
        console.log(error);
    })
  }, [])
  
  return(
  <div>
  capital: {searchedCountries.map(c => <p>{c.capital}</p>)}
  area: {searchedCountries.map(c => <p>{c.area}</p>)}
  <h2>Languages</h2>
  <ul>
  {
    searchedCountries.map(c =>
      
        <ul>
          {Object.values(c.languages).map(l => <li>{l}</li>)}
        </ul>
     
    )
  }
</ul>
  {searchedCountries.map(c => <img src={Object.values(c.flags)[0]} alt="" /> )}
  <h3>Weather</h3>
  <p>temperature is {weather.map(w => w.main.temp - 273.15)} degrees Celsius</p>
<p>wind is {weather.map(w => w.wind.speed)} miles per hour</p>
<img src={`http://openweathermap.org/img/wn/${iconname}.png`} alt="" />

        </div>
  )
}

const Countries = ({ searchedCountries, handleClick, show, setWeather, setCountries, weather}) => {
  if (weather === undefined) {
    return null
  }
  if (searchedCountries.length >= 10) {
    return (
      <div>
        <p>too many countries to list, please narrow your search</p>
      </div>
    )
  } 
  if (searchedCountries.length === 1) {
    return (
 <Singlecountry searchedCountries={searchedCountries} setWeather={setWeather} weather={weather}/>
    )
  }
  if (show === true) {
    return (
      <Singlecountry searchedCountries={searchedCountries} setWeather={setWeather} />
    )
  }
  return (
    <ul>
    {searchedCountries.map(c => <li>{c.name.common}<button onClick={handleClick} >show</button></li>)}
  </ul>
  )
}


const App = () => {
const [countries, setCountries] = useState([])
const [newSearch, setNewSearch] = useState('')
const [show, setShow] = useState(false)
const [weather, setWeather] = useState('')


const handleSearchChange = (event) => {
  setNewSearch(event.target.value)
}

const handleClick = () => {
 setShow(!show)
}

const searchedCountries = 
countries.filter(c => c.name.common.includes(newSearch))

useEffect(() => {
  axios
  .get('https://restcountries.com/v3.1/all')
  .then(response => {
    setCountries(response.data)
  })
}, [])


  return (
    <div>
<div><p>find countries</p><input value={newSearch} onChange={handleSearchChange} /></div>
<div>
  <h2>countries</h2>
  <Countries searchedCountries={searchedCountries} handleClick={handleClick} show={show} setCountries={setCountries} setWeather={setWeather} weather={weather}/>
</div>
    </div>
  )
}


export default App

下面的代码旨在当用户在搜索栏中输入国家名称时显示国家信息,包括首都、温度和天气。

该应用程序从国家 API 获取国家数据,当用户搜索特定国家时,它会从天气 API 获取天气。

但是,当应用程序刷新时,应用程序会在搜索单个国家/地区的天气时中断。

有谁知道这是为什么以及如何解决?

谢谢

看起来您在 useEffect 中使用 axios,这可能会导致无限循环并使您的应用程序崩溃。 我建议为您的数据获取创建一个单独的 function,然后像这样在useEffect中调用 function:

const fetchCountries = useCallback(() => {
  axios
  .get('https://restcountries.com/v3.1/all')
  .then(response => {
    setCountries(response.data)
  })
}, [])

useEffect(() => {
 fetchCountries()
}, [fetchCountries])

关键是useEffect中的依赖数组,只有当来自fetchCountries function 的国家列表发生变化时才会更新,从而防止无限循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM