Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

81
Visualizações
React.js con OpenWeatherMap, obtener weathers.map no es una función

Estoy aprendiendo React.js para la universidad y estoy un poco atascado. Estoy recibiendo este error:

 weathers.map not a function

¡Estoy seguro de que es algo simple pero no puedo resolverlo! Es una create-react-app , creó un directorio llamado componentes y estos 2 archivos viven allí:

Tiempos.js:

 import {useState} from 'react' import axios from 'axios' import Weather from './Weather' function Weathers() { const [weathers, setWeathers] = useState() const [city, setCity] = useState('') const API = { link: "http://api.openweathermap.org/data/2.5/weather?q=", key: "&appid=xxxxx" } function handleSearchCity(e) { e.preventDefault() setCity(e.target.value) } async function searchWeathers(e) { e.preventDefault() console.log() var response = await axios.get(API.link + city + API.key) console.log(response) setWeathers(response.data) } return ( <div> <input value={city} onChange={handleSearchCity} /> <button onClick={searchWeathers}>Search</button> <div> </div> { weathers.map(function(i, index){ return ( <div> <Weather name={i.name} /> </div> ) }) } </div> ) } export default Weathers;

Tiempo.js:

 function Weather(props) { return ( <div> {props.name} </div> ); } export default Weather;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Está recibiendo un error porque el resultado de la API no es una matriz. Es un objeto que se ve así (para Londres):

 { "coord": { "lon": -0.1257, "lat": 51.5085 }, "weather": [ { "id": 500, "main": "Rain", "description": "light rain", "icon": "10n" } ], "base": "stations", "main": { "temp": 278.91, "feels_like": 276.51, "temp_min": 277.25, "temp_max": 280.02, "pressure": 1021, "humidity": 88 }, "visibility": 10000, "wind": { "speed": 3.09, "deg": 330 }, "rain": { "1h": 0.89 }, "clouds": { "all": 100 }, "dt": 1646438029, "sys": { "type": 2, "id": 2019646, "country": "GB", "sunrise": 1646375984, "sunset": 1646415906 }, "timezone": 0, "id": 2643743, "name": "London", "cod": 200 }

Si desea la propiedad del name dentro del resultado, puede obtenerlo así:

 import {useState} from 'react' import axios from 'axios' import Weather from './Weather' function Weathers() { const [weathers, setWeathers] = useState() const [city, setCity] = useState('') const API = { link: "http://api.openweathermap.org/data/2.5/weather?q=", key: "&appid=xxxxx" } function handleSearchCity(e) { e.preventDefault() setCity(e.target.value) } async function searchWeathers(e) { e.preventDefault() console.log() var response = await axios.get(API.link + city + API.key) console.log(response) setWeathers(response.data) } return ( <div> <input value={city} onChange={handleSearchCity} /> <button onClick={searchWeathers}>Search</button> {weathers && <Weather name={weathers.name} />} </div> ) } export default Weathers;
about 4 years ago · Juan Pablo Isaza Relatório

0

Dado que weathers se inicializa en una matriz vacía, en realidad no debería tener el error weathers.map is not a function . Tal vez pueda agregar una representación condicional para devolver solo la expresión jsx cuando obtenga los datos meteorológicos de la API.

 return weathers && ( <div> // ... </div> ) } export default Weathers;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda