【问题标题】:I dont understand why ".map" is undefined in this variable我不明白为什么“.map”在这个变量中没有定义
【发布时间】: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.log noticias.articles 看看有什么数据给你
  • 似乎对newsapi.org 的请求失败(控制台中的第一个错误)
  • 进入此状态 const [noticias, guardarNoticias] = useState([]) 并在此变量中使用 const noticias = await resposta.json()。我把这个道具放在这里const ListadoNoticias = ({noticias}) =&gt;{

标签: javascript reactjs array.prototype.map


【解决方案1】:

问题

这里的问题是fetch 正在返回一个错误,并且您的响应处理不处理成功的失败响应,即错误的有效响应。在这种情况下,您会收到 426 错误状态代码。

您可能会将您的 noticias 设置为未定义的值。

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); // <-- 426 error response
    const noticias = await resposta.json();

    guardarNoticias(noticias.articles); // <-- articles undefined
  }
  consultarAPI();
}, [categoria]);

未定义的noticias 状态被传递给ListadoNoticias,您尝试从中映射并抛出错误。

解决方案

您应该真正将async/await 代码包围在try/catch 中,以处理被拒绝的承诺和其他各种抛出的错误。您还应该检查successful fetch

useEffect(() => {
  const consultarAPI = async () => {
    const API = '81673cba4b934873953af1db871a6ac7';
    const url = `https://newsapi.org/v2/top-headlines?country=br&category=${categoria}&apiKey=${API}`;

    try {
      const resposta = await fetch(url);
      if (!resposta.ok) {
        throw new Error('Network response was not ok');
      }
      const noticias = await resposta.json();
      guardarNoticias(noticias.articles);
    } catch(error) {
      // handle fetch failure or any other thrown errors
    }
  }
  consultarAPI();
}, [categoria]);

【讨论】:

  • 非常感谢@Drew Reese。现在唯一的错误是 426。我认为它来自 API。看这张图片:i.imgur.com/TLjy5Of.png
  • @YgorLourenco 似乎 HTTP status 426 是后端 API,建议您应根据请求升级使用的协议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 2015-08-31
  • 1970-01-01
  • 2019-04-21
  • 1970-01-01
  • 2013-07-23
相关资源
最近更新 更多