简体   繁体   English

如何从ReactJS中的JSON数组中获取项目?

[英]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 我正在尝试从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. 我不知道如何通过render方法提取数组中的项。 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... 我实际上在这里使用了这个问题: ReactJS可以访问JSON中的数组 ...到现在为止,我仍然无法正常工作...

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. fetch请求完成之前,不会设置weather数组,因此渲染方法中的this.state.items.weather.map将导致错误。

You could give weather an empty array as default value. 您可以给weather一个空数组作为默认值。

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. 复制此示例并将其粘贴到codeandbox.io中。您正在将构造函数中的项目初始化为array(其中fetch给您提供了一个对象),对于初始渲染,item.weather是未定义的,而在render方法中,您试图访问未定义的地图这是导致错误的原因。 (I have changed the url to https to run it in codesandbox) (我已将URL更改为https,以在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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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