【发布时间】:2019-09-13 10:43:15
【问题描述】:
我正在创建一个对 OpenWeather API 进行 API 调用的 React / .NET 应用程序。当我在城市的位置硬编码时,它工作得很好。但是,我希望用户能够将他们当前的城市输入到表单中,按提交,并更新天气详细信息。这是我当前的代码:
import React, { Component } from "react";
export class Home extends Component {
constructor(props) {
super(props);
this.state = { temp: "", summary: "", city: "", location: "London" };
}
getData() {
fetch("api/weather/city/" + encodeURIComponent(this.state.location))
.then(response => response.json())
.then(data =>
this.setState({
temp: data.temp,
summary: data.summary,
city: data.city
})
);
}
render() {
return (
<div>
<center>
<h1>Weather</h1>
<p>Please enter your city:</p>
<form onSubmit={() => this.getData()}>
<input
type="text"
placeholder="Type city here..."
value={this.state.location}
onChange={e => this.setState({ location: e.target.value })}
/>
<button type="submit">Submit</button>
</form>
<h4>City</h4>
<p>{this.state.city}</p>
<h4>Temperature</h4>
<p> {this.state.temp}</p>
<h4>Description</h4>
<p> {this.state.summary}</p>
</center>
</div>
);
}
}
每当我输入城市并按提交时,都不会显示任何 API 数据。但是,我已经测试了 API 调用,并且可以正常工作。有没有人可以帮助建议我如何获取用户的输入以更新 this.state.location 并显示该城市的天气?
非常感谢。
【问题讨论】:
-
你为什么使用encodeURIComponent?只需使用 this.state.location。由于openweather api如下,api.openweathermap.org/data/2.5/weather?q=London。名字就足够了
-
代码原样应该工作。您在控制台中看到任何错误吗?
-
尝试将选定的输入值从 jsx 本身传递给 getdata 函数或尝试 Comoponentonupdate 函数