【问题标题】:Getting data from openweather API in React从 React 中的 openweather API 获取数据
【发布时间】:2017-10-10 14:01:13
【问题描述】:

我正在尝试编写一个程序,将 2 个城市的名称作为输入,然后使用 openweathermap API 获取 2 个城市的温度。但是,我无法调用 API。我尝试遵循一些教程,但这有点令人困惑。如果有人可以帮助我连接 API、获取城市的温度并将它们打印在屏幕上,我会很高兴。

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import _ from 'lodash';
import Request from 'superagent';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {input1: '', input2: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({[event.target.name]: event.target.value});
  }

  componentDidMount(){
      var city1 = this.state.input1;
      var url= 'http://api.openweathermap.org/data/2.5/weather?q={city1}&units=metric&APPID=83c6ba4dd07d83514536821a8a51d6d5';
      Request.get(url).then((response) => {
          this.setState({
              report: response.body.Search
          });
      });
  }

  handleSubmit(event) {
      var temperature = _.map(this.state.report, (city) => {
          return (<p>{city.main.temp}</p>);
      });

    event.preventDefault();
  }

  render() {
      return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
        </header>
        <div className="container">
            <h1>Where Should I go?</h1>
            <form onSubmit={this.handleSubmit}>
            <div className="cityboxdiv">
                <input name="input1" type="text" id="tb1" className="citybox" onChange={this.handleChange} placeholder="Enter City1" autoFocus />
                <input name="input2" type="text" id="tb2" className="citybox" onChange={this.handleChange} placeholder="Enter City2"/>
            </div>
            <div className="btn-div">
                <button type="submit" className="sub-btn">Tell Me!</button>
            </div>
            </form>
        </div>
      </div>
    );
  }
}

export default App;

我想知道两件事是如何将城市名称传递到 url 中,以便我们可以获取数据。而一旦我们得到数据,我怎样才能只显示城市的温度值。

【问题讨论】:

    标签: reactjs api openweathermap


    【解决方案1】:

    我看到你犯了几个错误。

    1. 请求 API 并将数据放入您应该在 handleSubmit 中进行的声明(或更好地使用操作)。
    2. 在渲染方法中,您应该将状态数据输出为state.report.map(item =&gt; (&lt;div&gt;{city.main.temp}&lt;/div&gt;))
    3. 生成可以使用模板字符串 (https://docs.microsoft.com/en-us/scripting/javascript/advanced/template-strings-javascript) 制作的 url

    【讨论】:

      猜你喜欢
      • 2013-09-25
      • 1970-01-01
      • 2021-09-27
      • 2020-03-30
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2017-10-23
      • 2022-01-21
      相关资源
      最近更新 更多