简体   繁体   中英

How to loop in render with array data API React

I have data from API where when I use console log I read all data. When I want to rendering this data I see only the first index of the array.

API look like this:

aladinModel: (2) […]
​​
0: (48) […]
​​​
0: Object { DATS: "2019-10-20T23:00:00.000Z", TA: 12.1, RH: 93.3, … }
​​​
1: Object { DATS: "2019-10-21T02:00:00.000Z", TA: 11, RH: 95.1, … }
​​​
2: Object { DATS: "2019-10-21T05:00:00.000Z", TA: 12.4, RH: 96.5, … }

I want to display all values.

My code:

import React from "react";

export default class FetchRandomUser extends React.Component {
  state = {
    loading: true,
    dataAPI: null
  };

  async componentDidMount() {
    const url = "http://localhost:8000/?date=2019-10-26&station=1010&daysForward=5";
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);
    this.setState({ dataAPI: data.aladinModel[0], loading: false });
  }




  render() {
    if (this.state.loading) {
      return <div>loading...</div>;
    }

    if (!this.state.dataAPI) {
      return <div>Няма данни !</div>;
    }
    return (
      <div>
        <div>{this.state.dataAPI[0].DATS}</div>

      </div>
    );
  }
}
 constructor(props) {
    super(props);
    this.state = {
      loading: true,
      dataAPI: null
    };
  }
  async componentDidMount() {
    fetch("http://localhost:8000/?date=2019-10-26&station=1010&daysForward=5")
      .then(response => response.json())
      .then(data => {
        return data;
      })
      .catch(error => console.log(error));
    this.setState({ dataAPI: this.data, loading: false });
  }

  render() {
    if (this.state.loading) {
      return <div>loading...</div>;
    }

    if (!this.state.dataAPI) {
      return <div>Няма данни !</div>;
    }
    return this.state.dataAPI.map((data, i) => (
      <div key={i}>
        {data.DATS},{data.TA},{data.RH}
      </div>
    ));
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM