繁体   English   中英

未捕获的类型错误:无法读取未定义的属性(读取“名称”)-ReactJS

[英]Uncaught TypeError: Cannot read properties of undefined (reading 'name') - ReactJS

import Info from "./components/Info";
import Search from "./components/Search";
import axios from "axios";
import { useEffect, useState } from "react";

const App = () => {

  const API_KEY = `<REDACTED>`
  const baseURL = `http://api.weatherapi.com/v1/current.json?key=${API_KEY}&q=`

  const [weatherData, setWeatherData] = useState({})
  const [search, setSearch] = useState('London')
  const [error, setError] = useState('')

  useEffect(() => {
    axios.get(`${baseURL + search}`)
      .then(resp => {
        setWeatherData(resp.data)
      })
      .catch(error => setError(error.message))
  }, [search])

  console.log(weatherData.location.name);

  return (
    <div className="App">
      <h1 style={{ textAlign: 'center', marginBottom: '2rem' }}>{error}</h1>
      <Search setSearch={setSearch} />
      <div className="container">
        <Info weatherData={weatherData} />
      </div>
    </div>
  );
}

export default App;

我正在尝试创建一个天气应用程序来做出反应。 我正在使用您可以在代码中看到的天气 API(也许您也应该看看 API 结构)。 当我控制台登录weatherData.location时,我得到了正常的天气数据。 但是当我尝试weatherData.location.name时,我收到错误消息: Uncaught TypeError: Cannot read properties of undefined (reading 'name') 我两周前开始学习 React,所以我还是个初学者……谢谢。

当 API 尚未发送响应且天气数据仍为空时,就会发生这种情况。 我建议添加一个[loading,setLoading]状态并将其默认设置为 true。 然后在.then(resp =>函数中将其设置为 false。使用 if 语句检查加载是否为 false,如果是,则打印/渲染 weatherData 的内容。

您需要在 console.log 中添加三元运算符

比如 console.log(weatherData? location ? .name ) 或者你可以试试 console.log(weatherData && weatherData.location && weatherDataname.location.name)

它的发生是因为在初始状态下它无法读取 name 的值,因为它可能是一个空字符串。

试试这个方法。

暂无
暂无

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

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