首页 > 解决方案 > React API Fetch 不返回所有数据,但在索引时返回

问题描述

我的问题是我在 FetchData 类中获得了一个数据列表,购买它的列表。我尝试为国家/地区编制索引: 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;

国家.js

import React, { Component } from 'react'; 

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

标签: javascriptreactjsapireact-reduxcomponents

解决方案


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

  // 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

推荐阅读