【问题标题】:react useEffect hooks with axios cannot read property of undefined用 axios 反应 useEffect 钩子无法读取未定义的属性
【发布时间】:2020-06-05 03:29:36
【问题描述】:

这是基于本课程的练习 2.14 https://fullstackopen.com/en/part2/getting_data_from_server。

用户可以选择一个国家,然后显示该国家首都的天气信息。我的代码给了我错误无法读取未定义的属性“温度”

const Weather = ({ city }) => {
const [weatherDetails, setWeatherDetails] = useState([])

useEffect(() => {
    axios.get('http://api.weatherstack.com/current', {
        params: {
            access_key: process.env.REACT_APP_WEATHER_KEY,
            query: city
        }
    }).then(
        (response) => {
            setWeatherDetails(response.data)
        }
    )
}, [city])
console.log('weather', weatherDetails);

return (
    <div>
        <h3>Weather in {city} </h3>
        {weatherDetails.current.temperature}
    </div>
)}

基本上就是一行

{weatherDetails.current.temperature}

使我的代码崩溃。当我删除该行时,我可以通过 console.log 看到响应,但是有两个连续的日志

weather []
weather {request: {…}, location: {…}, current: {…}}

我认为我的代码发生在这两者之间,它甚至会在数据到达之前尝试访问数据,但我不知道如何解决这个问题。

另外,我不知道 useEffect() 的参数 [city] 是做什么的,所以如果有人可以向我解释它的作用,那就太好了。

编辑:已解决! 将weatherDetail的初始状态设置为null并进行了一些条件渲染

if (weatherDetails) {
    return (
        <div>
            <h3>Weather in {capital}</h3>
            {weatherDetails.current.temperature} Celsius
        </div>
    )
} else {
    return (
        <div>
            Loading Weather...
        </div>
    )
}

【问题讨论】:

    标签: reactjs axios react-hooks


    【解决方案1】:

    weatherDetails 最初是一个空数组,因此没有可读取的current 属性。

    使用一些conditional rendering。使用初始 null 状态,然后检查在更新时访问对象的其余部分是否真实。

    const Weather = ({ city }) => {
    const [weatherDetails, setWeatherDetails] = useState(null) // <-- use null initial state
    
    useEffect(() => {
        axios.get('http://api.weatherstack.com/current', {
            params: {
                access_key: process.env.REACT_APP_WEATHER_KEY,
                query: city
            }
        }).then(
            (response) => {
                setWeatherDetails(response.data)
            }
        )
    }, [city])
    console.log('weather', weatherDetails);
    
    return (
        <div>
            <h3>Weather in {capital} </h3>
            {weatherDetails && weatherDetails.current.temperature} // check that weatherDetails exists before accessing properties.
        </div>
    )}
    

    useEffect 的参数 [city] 有什么作用?

    这是钩子的依赖数组。钩子在每个渲染周期运行,如果依赖数组中的任何值发生了更新,它会触发钩子的回调,在这种情况下,当city 属性更新时获取天气数据的效果。

    useEffect

    默认情况下,效果会在每次完成渲染后运行,但您可以 选择仅在某些值发生更改时触发它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 2018-05-24
      • 2021-07-25
      • 2020-08-23
      • 2021-12-27
      相关资源
      最近更新 更多