【发布时间】:2026-02-21 04:25:01
【问题描述】:
我只是对天气应用做出反应,我从中选择了一个城市,之后我需要重新加载数据。基本上,它工作正常。但是换城后,我的子组件显示新数据,旧数据,重复几次,之后组件显示好数据。怎么了?
我尝试从组件生命周期方法中实现一些功能,但没有成功。
import React, { Component } from 'react';
import './App.css';
import Form from "./Components/Form"
import Overcast from "./Components/Overcast"
import Forecast from "./Components/Forecast"
class App extends Component {
constructor(props) {
super()
this.state = {
forecasts: [{}],
selectedCity: 1
}
this.handleCityChange = this.handleCityChange.bind(this)
this.fetchForeacst = this.fetchForeacst.bind(this)
}
componentDidMount() {
var today = new Date()
var day = String(today.getDate()).padStart(2, '0')
var month = String(today.getMonth() + 1).padStart(2, '0')
var year = String(today.getFullYear())
today = year + '-' + month + '-' + day
this.fetchForeacst(today)
}
componentDidUpdate() {
var today = new Date()
var day = String(today.getDate()).padStart(2, '0')
var month = String(today.getMonth() + 1).padStart(2, '0')
var year = String(today.getFullYear())
today = year + '-' + month + '-' + day
this.fetchForeacst(today)
}
fetchForeacst(date) {
const WEATHER_API = 'http://dev-weather-api.azurewebsites.net/api/city/' + this.state.selectedCity + '/weather?date=' + date + ''
fetch(WEATHER_API)
.then(response => response.json())
.then(data => this.setState({forecasts: data}))
}
handleCityChange(city) {
this.setState({selectedCity: city})
}
render() {
return (
<div className="App">
<Form handleChange={this.handleCityChange}/>
<Overcast forecast={this.state.forecasts[0]} />
<Forecast forecasts={this.state.forecasts} />
</div>
)
}
}
export default App;
我没有任何错误或什么的。
【问题讨论】: