【问题标题】:React API Fetch Not Returning All Data But Does When IndexingReact API Fetch 不返回所有数据但在索引时返回
【发布时间】:2021-02-21 19:49:00
【问题描述】:

我的问题是我在 FetchData 类中获得了一个数据列表,请购买它的列表。我尝试为 countries: data.Countries[0] 建立索引,例如 0 它给了我这些值,但我希望所有数据都可以在此进行 foreach ?

使用国家/地区的索引获取:data.Countries[0]

获取不带国家/地区索引的数据:data.Countries

fetchData.js


import React, { Component } from 'react';
import Countries from './countries';

class FetchData extends Component {
    
    state = {
        loading: true,
        countries: null
    };

    async componentDidMount() {
        const url = 'https://api.covid19api.com/summary';
        const response = await fetch(url);
        const data = await response.json();
        this.setState({
            countries: data.Countries,
            loading: false
        });
    }
     
  render() {
    return (
        <div>
            {this.state.loading || !this.state.countries ? ( 
            <div>loading</div>
            ) : (
            <div> 
                <Countries WorldCountries={this.state.countries.Country} /> 
            </div>
            )}
        </div>
    );
  }
}

export default FetchData;

countries.js

import React, { Component } from 'react'; 

const Countries = (prop) => {
    return(
    <h1>{prop.Countries}</h1>
    );
}
export default Countries;

【问题讨论】:

  • 您将“WorldCountries”作为道具传递,但为什么在国家组件中您正在寻找“prop.Countries”?
  • @EmadEmami 哦,我的错误是在尝试一些东西,但我将其改回 prop.WorldCountries。

标签: javascript reactjs api react-redux components


【解决方案1】:

您的图片让我感到困惑,但如果我理解正确,您需要执行以下操作:

  // FetchData component
  ...
  render() {
    return (
        <div>
            {this.state.loading || !this.state.countries ? ( 
            <div>loading</div>
            ) : (
            <div>
              {
                this.state.countries.map(country =>
                    <Country country={country.Country} />)
              }
            </div>
            )}
        </div>
    );
  }
  ...
  // FetchData component 


  // Country component
  const Countries = ({ country }) => (
    <h1>{country}</h1>
  );
  // Country component

【讨论】:

  • 我收到 TypeError 错误:this.state.countries.map is not a function
  • @abdullahalhamidi 你在 this.state.countries 有什么?你为国家 data.Countries[0] 或 data.Countries 设置了什么?
  • 多个列表 {"Country":"Albania","CountryCode":"AL","Slug":"albania","NewConfirmed":501,"TotalConfirmed":24206,"NewDeaths" :2,"TotalDeaths":559,"NewRecovered":90,"TotalRecovered":12092,"Date":"2020-11-09T21:01:31Z","Premium":{}}
  • 每个国家/地区的列表更多
  • 哦,成功了!我不得不更改变量 )它是 )谢谢!
猜你喜欢
  • 2018-11-12
  • 2021-11-04
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 2021-02-17
相关资源
最近更新 更多