简体   繁体   中英

How to get an item from an array in JSON in ReactJS?

I am trying to get an item "icon" from "weather" form following JSON

{
  "coord": {
    "lon": 14.33,
    "lat": 49.94
  },
  "weather": [{
    "id": 800,
    "main": "Clear",
    "description": "clear sky",
    "icon": "01d"
  }]
}

I can't figure out how to exctract an item which is in array through render method. My code is:

class Weather extends React.Component {
  constructor() {
    super();
    this.state = {
      'items': []
    }
  }

  componentDidMount() {
    this.getItems();
  }

  getItems() {
    fetch('http://api.openweathermap.org/data/2.5/weather?lat=49.9415967&lon=14.3316786&appid=ed62e370682cc9e4144620905eff37e4')
    .then(results => results.json())
    .then(results => this.setState ({'items': results}));
  }

  render() {
    return (
        <div>
            <h1>here should be an icon..</h1>
            {this.state.items.weather.map(function(weather, index) {
                return <h3 key={index}>{weather.icon}</h3>
            })}
        </div>
    );
  }
}

I actually used this question here: Get access to array in JSON by ReactJS ...which got me this far, but still can't make it working...

Your weather array is not set until your fetch request is complete, so this.state.items.weather.map in your render method will result in an error.

You could give weather an empty array as default value.

class Weather extends React.Component {
  constructor() {
    super();
    this.state = {
      items: {
        weather: []
      }
    };
  }

  componentDidMount() {
    this.getItems();
  }

  getItems() {
    fetch(
      "http://api.openweathermap.org/data/2.5/weather?lat=49.9415967&lon=14.3316786&appid=ed62e370682cc9e4144620905eff37e4"
    )
      .then(results => results.json())
      .then(results => this.setState({ items: results }));
  }

  render() {
    return (
      <div>
        <h1>here should be an icon..</h1>
        {this.state.items.weather.map(function(weather, index) {
          return <h3 key={index}>{weather.icon}</h3>;
        })}
      </div>
    );
  }
}

copy paste this example in codesandbox.io .you were initializing the items in constructor as array(where as fetch gave you an object) and for the initial render, items.weather was undefined and in render method you were trying to access map of undefined which was causing the error. (I have changed the url to https to run it in codesandbox)

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      items: {}
    };
  }

  componentDidMount() {
    this.getItems();
  }

  getItems() {
    fetch(
      "https://api.openweathermap.org/data/2.5/weather?lat=49.9415967&lon=14.3316786&appid=ed62e370682cc9e4144620905eff37e4"
    )
      .then(results => results.json())
      .then(results => this.setState({ items: results }));
  }

  render() {
    return (
      <div>
        <h1>here should be an icon..</h1>
        {this.state.items.weather &&
          this.state.items.weather.map(function(weather, index) {
            return <h3 key={index}>{weather.icon}</h3>;
          })}
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

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