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以便我们可以获取数据。一旦我们获得了数据,我怎样才能显示城市的温度值。