无法读取未定义的属性(读取“0”)- API 问题

问题描述 投票:0回答:1

我从没想过我必须提出自己的问题,但我来了。我是反应新手。 我在从 API 获取特定数据时遇到问题。其他都还好,但是有

src={
https://openweathermap.org/img/wn/${cityData?.weather[0]?.icon}@2x.png
}

我收到错误“无法读取未定义的属性(读取“0”)

完整代码如下:

import React, { useEffect, useState } from "react"
import { Outlet } from "react-router-dom"
import sun from '../assets/sun.png'

export default function Weathertab(props){
    
    const [cityData, setCityData] = useState({})
    const apiKey = "b708966eb167246df9118941d4bddc31"
    const cityWeatherData = `https://api.openweathermap.org/data/2.5/weather?q=${props.city}&units=Metric&appid=${apiKey}`

    useEffect(function(){
        async function fetchData(){
            await fetch(cityWeatherData)
                .then(res=> res.json())
                .then(data => setCityData(data))
        }
        fetchData()
    }, [])

    console.log(cityData)
    console.log(props.city)
    return(
        <div className="weather--tab">
            <img className="weather--icon" 
                    src={`https://openweathermap.org/img/wn/${cityData?.weather[0]?.icon}@2x.png`}
                    alt="sun behind a cloud" />
            <h1 className="weather--tab--degrees">{Math.floor(cityData?.main?.temp)}°C</h1>
            <h3 className="weather--tab--city">{props.city}</h3>
            <div className="weather--min--max--temp">
                <div className="weather--block">
                    <label>Min Temp</label>
                    <p className="weather--min--max" id="weather--min">{Math.floor(cityData?.main?.temp_min)}°C</p>
                </div>
                <div className="weather--block">
                    <label>Max Temp</label>
                    <p className="weather--min--max" id="weather--max">{Math.floor(cityData?.main?.temp_max)}°C</p>  
                </div>
            </div>
            <Outlet />
        </div>
    )
}

我尝试用谷歌搜索这个问题(以及它),但没有任何帮助。问题仅在于 cityData.weather[0].icon

我尝试在useEffect函数中将useState和setTheIcon设置为cityData.weather[0].icon,但没有成功。

为什么它适用于 cityData?.main?.temp,但不适用于 cityData?.weather[0]?.icon?

reactjs api
1个回答
0
投票

您在 cityData?.weather[0]?.icon 中看到问题的原因可能是因为 cityData 最初是一个空对象 {}。当您的组件首次呈现时,cityData.weather 未定义的原因是检索天气数据的 API 调用仍处于挂起状态。访问未知值的 [0] 将导致错误。

获取数据后,您可以有条件地渲染天气图标来解决此问题。在访问其任何元素之前,您可以使用 && 运算符来查看 cityData.weather 是否存在。这是更改代码的方法:

import React, { useEffect, useState } from "react"
import { Outlet } from "react-router-dom"
import sun from '../assets/sun.png'

export default function Weathertab(props){
    
    const [cityData, setCityData] = useState({})
    const apiKey = "b708966eb167246df9118941d4bddc31"
    const cityWeatherData = `https://api.openweathermap.org/data/2.5/weather?q=${props.city}&units=Metric&appid=${apiKey}`

    useEffect(function(){
        async function fetchData(){
            await fetch(cityWeatherData)
                .then(res=> res.json())
                .then(data => setCityData(data))
        }
        fetchData()
    }, [])

    console.log(cityData)
    console.log(props.city)
    return(
        <div className="weather--tab">
            {cityData.weather && (
                <img className="weather--icon" 
                    src={`https://openweathermap.org/img/wn/${cityData.weather[0].icon}@2x.png`}
                    alt="sun behind a cloud" />
            )}
            <h1 className="weather--tab--degrees">{Math.floor(cityData?.main?.temp)}°C</h1>
            <h3 className="weather--tab--city">{props.city}</h3>
            <div className="weather--min--max--temp">
                <div className="weather--block">
                    <label>Min Temp</label>
                    <p className="weather--min--max" id="weather--min">{Math.floor(cityData?.main?.temp_min)}°C</p>
                </div>
                <div className="weather--block">
                    <label>Max Temp</label>
                    <p className="weather--min--max" id="weather--max">{Math.floor(cityData?.main?.temp_max)}°C</p>  
                </div>
            </div>
            <Outlet />
        </div>
    )
}

通过在标签周围添加 {cityData.weather && (...)} ,可以确保仅当 cityData.weather 为 true 时才呈现图标,从而避免“无法读取未定义的属性”错误。

© www.soinside.com 2019 - 2024. All rights reserved.