【问题标题】:State not fetching API data on submit状态未在提交时获取 API 数据
【发布时间】: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;

【问题讨论】:

  • 我的回答对你有帮助吗?

标签: reactjs api


【解决方案1】:

所以你有一个componentDidMount 方法,但你不处理状态的更新。 你需要一个componentDidUpdate 方法

componentDidUpdate(prevProps, prevState) {
  if (prevState.city !== this.state.city) {
    this.fetchData();
  }
}

【讨论】:

  • 非常感谢您的帮助。我所做的只是将我的 componentDidMount 更改为 componentDidUpdate 并且它立即工作。不要以为没有你的帮助我会想出那个。
  • 好的,请接受我的回答,这个问题将被视为“已回答”。谢谢,欢迎使用 stackoverflow!
猜你喜欢
  • 2022-01-15
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
  • 2019-01-23
  • 2017-07-30
  • 2014-12-08
  • 2019-12-07
相关资源
最近更新 更多