【发布时间】:2020-07-09 21:02:02
【问题描述】:
第一个 stackoverflow 帖子。 React 新手(1 周)并使用 API 获取请求来了解道具、状态和组件。
我正在使用天气 API 来获取特定城市的温度。用户在表单中输入城市,点击提交,显示温度。
当我通过输入一个城市作为测试来对 selectedCity 状态进行硬编码时,我可以在 DevTools 中看到获取了该城市的 API 数据,并且该城市的温度显示在浏览器中。问题是当我单击表单组件上的提交时。在提交时,我可以在 DevTools 中看到它使用用户选择的城市更新 selectedCity 状态,但它不获取数据。我注意到,在城市中进行硬编码时,页面刷新并获取数据并显示结果,但是通过表单提交时页面没有刷新。
我对 React 的了解还不够,无法弄清楚这里发生了什么。感谢任何指点。
这是我的 WeatherContainer
import React, { Component } from 'react';
import Headings from '../components/Headings';
import Form from '../components/Form';
import Weather from '../components/Weather';
class WeatherContainer extends Component {
constructor(props) {
super(props);
this.state = {
weatherData: [],
selectedCity: ""
};
this.handleFormSubmit = this.handleFormSubmit.bind(this);
}
fetchData() {
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${this.state.selectedCity}&APPID=MyAPIKey`)
.then(res => res.json())
.then(result => this.setState({ weatherData: result.main }))
}
componentDidMount() {
this.fetchData();
}
handleFormSubmit({city}) {
this.setState({selectedCity: city})
}
render() {
return (
<div>
<Headings />
<Form onFormSubmit={this.handleFormSubmit} />
<Weather weather={this.state.weatherData} />
</div>
);
}
}
export default WeatherContainer;
这是我的表单组件
import React, { Component } from 'react';
class Form extends Component {
constructor(props) {
super(props);
this.state = {
city: ""
};
this.handleCityChange = this.handleCityChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const city = this.state.city;
if (!city) {
return
}
this.props.onFormSubmit({
city: city
});
this.setState({
city: ''
})
}
handleCityChange(event) {
this.setState({
city: event.target.value
})
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.city}
placeholder="Enter City"
onChange={this.handleCityChange}
/>
<input type="submit" value="Submit" />
{/* <button>Get Weather</button> */}
</form>
);
}
}
export default Form;
我的天气组件
import React from 'react';
const Weather = ({ weather }) => {
if(!weather) return null
return (
<div>
<h1>{weather.temp}</h1>
</div>
);
}
export default Weather;
【问题讨论】:
-
我的回答对你有帮助吗?