Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

226
Views
No se pueden leer las propiedades de React indefinido. El registro solo funciona en el objeto

Actualmente estoy tratando de crear un sitio web meteorológico usando weatherapi, pero tengo un problema. Si registro el objeto de ubicación, no hay error, pero si intento registrar algo más profundo que ese objeto, como el nombre de la ciudad, no puede leer las propiedades de indefinido. Si comento el registro cuando usa el nombre de la ciudad, luego lo elimino nuevamente y no vuelvo a cargar la página, entonces registrará el nombre de la ciudad sin error.

 import React from 'react'; import './index.css'; import Navbar from "./components/Navbar" import {useState} from "react" import Weather from './components/Weather'; function App() { const [inputData, setInputData] = useState({}) const [currentWeather, setCurrentWeather] = useState([]) const [loc, setLoc] = useState({loc:"Arlington"}) let apiKey = "xxxxxxxx" // console.log("Location: "+ loc.loc) React.useEffect(() =>{///Finds weather data of certain location console.log(loc.loc) fetch(`https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${loc.loc}&aqi=no`) .then(res => { if(res.ok){ return res.json() } }) .then(data => { if(data !=null){//Only change currentWeather when there is data for it setCurrentWeather(data) }else{ alert(`${loc.loc} was not found`) } }) }, [loc]) React.useEffect(() =>{///Finds locations with search bar fetch(`https://api.weatherapi.com/v1/search.json?key=${apiKey}&q=${loc.loc}&aqi=no`) .then(res => res.json()) .then(data => { if(data.loc == null){ }else{ setLoc(data) } }) }, []) //console.log(currentWeather.location.name) return ( <div className="App"> <Navbar inputData={inputData} setLoc={setLoc} setInputData={setInputData}/> <Weather currentWeather={currentWeather}/> </div> ); } export default App;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Algunos problemas que veo:

  1. Está inicializando currentWeather en una matriz, pero probablemente debería ser undefined o un objeto ( {} ) en función de su uso. Para arreglar esto, use uno de estos:
 const [currentWeather, setCurrentWeather] = useState() // or const [currentWeather, setCurrentWeather] = useState({})
  1. Está intentando acceder a currentWeather.location.name antes de haber actualizado currentWeather para tener esas propiedades. Por eso te da ese error.

La mejor solución para esto es usar el encadenamiento opcional https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Así que prueba esto:

 console.log(currentWeather?.location?.name)
  1. Su console.log está solo en el cuerpo del componente de la función, lo que significa que solo se llamará una vez (con el valor inicial), creo. Para solucionar esto y registrar cada vez que cambia el valor de currentWeather , puede hacer esto en su lugar:
 React.useEffect(() => { console.log(currentWeather?.location?.name) }, [currentWeather])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!