【问题标题】:How to get an item from an array in JSON in ReactJS?如何从 ReactJS 中的 JSON 数组中获取项目?
【发布时间】:2018-12-10 12:53:46
【问题描述】:

我正在尝试从 JSON 之后的“天气”表单中获取项目“图标”

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

我不知道如何通过渲染方法提取数组中的项目。 我的代码是:

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>
    );
  }
}

我实际上在这里使用了这个问题:Get access to array in JSON by ReactJS ...这让我走到了这一步,但仍然无法使其正常工作...

【问题讨论】:

  • 正如@Tholle 指出的那样,您应该在项目中添加天气键,或者如果您只关心天气,您可以将状态与项目键作为数组并在设置状态时,只需这样做this.setState({ 'items': results.weather })
  • 在这种情况下,它只是 console.logs undefined...

标签: arrays json reactjs


【解决方案1】:

在您的fetch 请求完成之前,不会设置您的weather 数组,因此您的渲染方法中的this.state.items.weather.map 将导致错误。

你可以给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>
    );
  }
}

【讨论】:

    【解决方案2】:

    将此示例复制粘贴到codesandbox.io 中。您将构造函数中的项目初始化为数组(其中 fetch 为您提供了一个对象),并且对于初始渲染,items.weather 未定义并且在您尝试访问的渲染方法中导致错误的未定义映射。 (我已将 url 更改为 https 以在代码和框中运行它)

    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);
    

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 2018-10-10
      相关资源
      最近更新 更多