【问题标题】:Pulling information from OpenWeatherMap API when state (country) changes当州(国家)发生变化时从 OpenWeatherMap API 中提取信息
【发布时间】:2022-01-28 07:40:06
【问题描述】:

目前,我只能在加载国家名称时提取信息,我添加代码,保存它,然后在 localhost 上更新。但是当我在另一个国家/地区输入时,我收到了Uncaught TypeError: Cannot read properties of undefined (reading 'temp') 的错误。例如,我的代码 {weather.main.temp} 有效,但前提是之前已经设置了 state = "france"。

我的子组件:

const WeatherInfo = ({ country }) => {
    const [weather, setWeather] = useState({});
    useEffect(() => {
        axios
            .get(`https://api.openweathermap.org/data/2.5/weather?q=${country.capital}&appid=${api_key}&units=imperial`)
            .then(response => {
                console.log(response.data)
                setWeather(response.data)
            })
    }, [country])
    return (
        <div>
            <h3>Weather in {country.capital}</h3>
            <p><b>Temperature</b>{weather.main.temp}</p>
        </div>
    )
}

【问题讨论】:

    标签: javascript reactjs axios


    【解决方案1】:

    weather 在创建WeatherInfo 时被初始化为空对象。因此weather.main 是未定义的,当您尝试从未定义中获取属性temp 时会出现错误。

    weather 为空对象时,您可以通过一些条件链接或一些三元运算符来解决此问题,具体取决于您希望显示的内容。

    return (
        <div>
            <h3>Weather in {country.capital}</h3>
            <p><b>Temperature</b>{weather.main?.temp}</p>
        </div>
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 2019-05-27
      • 2014-02-24
      • 1970-01-01
      相关资源
      最近更新 更多