【问题标题】:Getting TypeError: news.map is not a function. What do I miss?获取 TypeError:news.map 不是函数。我想念什么?
【发布时间】:2020-08-14 20:25:42
【问题描述】:

我正在创建一个 React 新闻应用程序,但我不知道为什么我在尝试获取和映射数据时收到此错误“TypeError: news.map is not a function” .

这是我的代码:

import React, {useState} from 'react';
import "./App.scss"
import axios from "axios"
import Article from "./Components/Article/Article"

function App() {

  const [news, setNews] = useState([]);

  const apiURL = "https://newsapi.org/v2/top-headlines?country=us&apiKey=287364824682742902893";

    const fetchData = async () => {
        const response = await axios.get(apiURL)

        setNews(response.data) 
        console.log(response.data)
    }

  return (
    <div className="App">

          {news.map(articles => (
            <Article title={articles.title} />
          ))} 

    </div>
  );
}

export default App;

console.log(response.data)

【问题讨论】:

    标签: javascript arrays reactjs axios fetch


    【解决方案1】:

    你得到的response.data是一个对象,它没有映射方法(我访问了你代码中的链接来查看它)

    假设你应该改写 setNews(response.data.someProperty),其中 someProperty 是对象中的数组

    更新:setNews(response.data.articles)

    【讨论】:

    • 是的,我在想这可能是因为它是一个对象,但我不完全明白我应该在我的代码中更改什么?
    • 需要查看您的 response.data 才能正确回答 :) 简而言之 - 这行 setNews(response.data)。你应该为 setNews 提供一个有效的数组
    • console.log(response.data) i.stack.imgur.com/2Peza.png
    【解决方案2】:

    您需要输入:setNews(response.data.articles)

    后来:

    <div className="App">
            {news.map(({ author, title }, i) => (
                <div key={i}>
                    <div>{author}</div>
                    <div>{title}</div>
                </div>
            ))}
        </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多