【问题标题】:When I update my state from form in react, my data in child components, gets strange behavior当我在反应中从表单更新我的状态时,我在子组件中的数据会出现奇怪的行为
【发布时间】: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;

我没有任何错误或什么的。

【问题讨论】:

    标签: json reactjs api


    【解决方案1】:

    您在 didUpdate 上调用 fetch api,这会触发 setState,它会一次又一次地调用 didUpdate。这就是你看到循环的原因。您应该将 fetch 包装在这样的 if 语句中:

     componentDidUpdate(prevProps, prevState) {
        if(prevState.selectedCity !== this.state.selectedCity) {
            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)      
         }
    }
    

    希望这会有所帮助。快乐编码。

    【讨论】:

    • 伙计!你很棒!非常感谢;)
    最近更新 更多