【问题标题】:React: cant get data via APIReact:无法通过 API 获取数据
【发布时间】:2021-11-30 09:23:30
【问题描述】:

我是 React 新手。我试图通过 APı 获取数据,但我无法获取任何数据。此外,我也没有收到任何错误消息。这是我的代码。我尝试添加 if 语句来检查是否获取数据。当我检查控制台时,我收到了错误消息。我哪里错了?感谢您的宝贵时间。

import React, {Component} from "react";

  class PokemonList extends Component {
  constructor(props) {
      super(props);
      this.state = {
      error: null,
      isLoaded: false,
      items: [],
    };
  }

componentDidMount() {
  fetch('https://pokeapi.co/api/v2/pokemon?limit=20')
    .then(res => res.json())
    .then(
      (result) => {
        this.setState({
          isLoaded: true,
          items: result.items
        });
      },
      // Note: it's important to handle errors here
    // instead of a catch() block so that we don't swallow
    // exceptions from actual bugs in components.
      (error) => {
        this.setState({
          isLoaded: true,
          error
        });
      }
    )
}
render() {
  const { error,isLoaded, items } = this.state;
  if (error) {
    return <div>Error: {error.message}</div>;
   } else if (!isLoaded) {
   return <div>Loading...</div>;
  } else {
      
    return (
        
        <ul>
        {items ? items.map(item => (
          <li>
             <p key={item.id}>{item.name}</p>;
          </li>
        )) :
        console.log('no data')}
      </ul>
    );
  }
}

} 导出默认 PokemonList;

【问题讨论】:

    标签: reactjs ajax react-native api


    【解决方案1】:

    您尝试获取的神奇宝贝物品有一个results 键,而不是items。所以将result.items 替换为result.results 看看会发生什么。

    【讨论】:

    • 您可以随时在浏览器中查看 json 数据,以便快速了解其结构。并且您可以安装一些浏览器扩展程序以使其像这样可读chrome.google.com/webstore/detail/json-formatter/…
    • 我怎么知道?它写在任何地方吗?我只是要求下一个项目。
    • 现在我得到了这个错误::无法读取未定义的属性(读取“地图”)
    • 对不起,我不明白你的问题。您是否通过进行我建议的更改来加载数据?
    • 我怎么知道它是结果键或结果项。有没有这样定义的地方?
    猜你喜欢
    • 2021-09-24
    • 1970-01-01
    • 2021-06-10
    • 2013-10-20
    • 1970-01-01
    • 2021-12-11
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多