2017-10-10 62 views
0

我在編寫一個程序,以2個城市的名稱作爲輸入,然後使用openweathermap API獲取2個城市的溫度。但是,我無法調用API。我嘗試了一些教程,但它有點混亂。如果有人能夠幫助我連接到API並獲取城市的溫度並將其打印在屏幕上,我會很高興。在React中從openweather 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以便我們可以獲取數據。一旦我們獲得了數據,我怎樣才能顯示城市的溫度值。

回答