繁体   English   中英

当我从react中的表单更新状态时,子组件中的数据会出现奇怪的行为

[英]When I update my state from form in react, my data in child components, gets strange behavior

我只需要在天气应用程序中做出反应,然后从中选择一个城市,然后就需要重新加载数据。 基本上,它工作正常。 但是,在城市变更之后,我的子组件显示了新数据,旧数据,并重复了几次,然后,这些组件显示了好数据。 怎么了?

我尝试从组件生命周期方法中实现一些功能,但是没有用。

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;

我没有任何错误。

您在didUpdate上调用fetch api,这会触发setState,该状态会一次又一次地调用didUpdate。 这就是为什么您看到循环。 您应该将获取内容包装在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)      
     }
}

希望这可以帮助。 快乐的编码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM