我正在创建一个 React / .NET 应用程序,该应用程序对 OpenWeather API 进行 API 调用。当我在城市位置进行硬编码时,它工作得很好。然而,我希望用户能够将他们当前的城市输入到表单中,按提交,并更新天气详细信息。这是我当前的代码:
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
并显示该城市的天气?
即使您的 api 给出了正确的结果,由于本机浏览器提交功能,页面也会刷新。
您应该使用
event.preventDefault
避免提交时默认刷新
<form onSubmit={(e) => this.getData(e)}>
getData(e) {
e.preventDefault()
如果发生任何其他错误,请告诉我。
希望有帮助!!!
您似乎从 api 结果映射了错误的值。
temp 必须取自:data.main.temp
摘要必须取自:data.weather[0].description
另外,正如评论中所建议的,encodeURIComponent 看起来没有必要。
你的 getData 函数必须是这样的。 我添加了 e.preventDefault();并更正了映射。
getData = (e) => {
e.preventDefault();
fetch("api/weather/city/" + encodeURIComponent(this.state.location))
.then(response => response.json())
.then(data =>
{
this.setState({
temp: data.main.temp,
summary: data.weather[0].description,
city: data.name
})
}
).catch(err => console.log("err:", err));
}
formSubmit 行可以更改为:
<form onSubmit={this.getData}>