【发布时间】:2021-07-31 07:50:33
【问题描述】:
这个 .map 对象是未定义的,但我不知道为什么。这一行 "{noticias.map((noticia) => ("
import React from 'react'
import Noticia from './Noticia'
import PropTypes from 'prop-types'
const ListadoNoticias = ({noticias}) =>{
return (
<div className='row'>
{noticias.map((noticia) => (
<Noticia
key={noticia.url}
noticia={noticia}
/>
))}
</div>
)
}
ListadoNoticias.propTypes = {
noticias: PropTypes.array.isRequired
}
export default ListadoNoticias;
“noticias”变量来自这里
import React, {Fragment, useState, useEffect} from 'react'
import Header from './components/Header'
import Formulario from './components/Formulario'
import ListadoNoticias from './components/ListadoNoticias'
function App() {
// Definir a categoria e noticia
const [categoria, guardarCategoria] = useState('') // Esse State guarda a categoria da noticia no hooks
const [noticias, guardarNoticias] = useState([]) // Vai guadar o array de objetos da requisição em formato JSON
useEffect(() => {
const consultarAPI = async () => {
const API = '81673cba4b934873953af1db871a6ac7'
const url = `https://newsapi.org/v2/top-headlines?country=br&category=${categoria}&apiKey=${API}`
const resposta = await fetch(url)
const noticias = await resposta.json()
guardarNoticias(noticias.articles)
}
consultarAPI()
}, [categoria]) // Vai usar esse State para mudar as informações da API
return (
<Fragment>
<Header
titulo='Buscador de Noticias'
/>
<div className='container white'>
<Formulario
guardarCategoria={guardarCategoria}
/>
<ListadoNoticias
noticias={noticias}
/>
</div>
</Fragment>
);
}
export default App;
奇怪的是,这段代码在 localhost 上运行。但是当我上传到 Netlify 时,它会在控制台上返回此错误。请看这张图:Error image in Netlify
【问题讨论】:
-
你能说明你在哪里传递那个道具吗?
-
他已经做到了
-
很确定
noticias.articles不是一个数组。 Console.lognoticias.articles看看有什么数据给你 -
似乎对
newsapi.org的请求失败(控制台中的第一个错误) -
进入此状态
const [noticias, guardarNoticias] = useState([])并在此变量中使用const noticias = await resposta.json()。我把这个道具放在这里const ListadoNoticias = ({noticias}) =>{
标签: javascript reactjs array.prototype.map