【问题标题】:React class component state value not updatingReact 类组件状态值未更新
【发布时间】:2022-01-07 08:47:38
【问题描述】:

我是反应 js 的新手。我通过创建一个简单的应用程序来学习它。我尝试使用 react 类组件创建一个简单的天气应用程序。一切正常,但存储在状态变量中的结果未在模板中打印。我可以在控制台中看到 API 响应,然后将结果存储在模板中未显示的“currWeatherRes”状态变量中(位置始终为空白)

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  
  constructor(){
    super();

    this.state = {
        cityName: "",
        currWeatherRes: {}
    }
}

  handleSubmit = (event) => {
    event.preventDefault();
    alert(`The name you entered was:`+ this.state.cityName);

      fetch(`https://api.openweathermap.org/data/2.5/weather?q=`+this.state.cityName+`&appid=f3ee66722740d00cc6f197cbcab3d534`, {
        method: 'GET'
      }).then((response) => {
        console.log(response)
        this.setState({
          currWeatherRes: response
        })
        //return response.json();
      });
  }

  handleChange = (event) => {
    this.setState({cityName:event.target.value});
  }

  render() {
    return (
      <div className="weather-app">
          <form onSubmit={this.handleSubmit}>
            <input type="text" value={this.state.cityName} onChange={this.handleChange} placeholder="Enter City"/>
            <button type="submit" value="Submit">Submit</button>
          </form>
          {(typeof this.state.currWeatherRes.main != "undefined") ? (
              <div className="weather-details">
                  <div className="weather-location">
                      <div className="location">Loctaion: {this.state.currWeatherRes.name}</div>
                  </div>
              </div>
          ):('')}
      </div>
    );
  }
}

export default App;

【问题讨论】:

    标签: javascript reactjs class state


    【解决方案1】:

    问题与 react 无关,而与您处理 API 调用的方式有关。

    修复:

    fetch(`https://api.openweathermap.org/data/2.5/weather?q=`+this.state.cityName+`&appid=f3ee66722740d00cc6f197cbcab3d534`, {
            method: 'GET'
          }).then((response) => {
            return response.json();
          }).then((res) => {
            this.setState({
              currWeatherRes: res
            })
          });
    

    工作代码:

    import React, { Component } from 'react';
    
    
    class App extends Component {
      
      constructor(){
        super();
    
        this.state = {
            cityName: "",
            currWeatherRes: {}
        }
    }
    
      handleSubmit = (event) => {
        event.preventDefault();
        alert(`The name you entered was:`+ this.state.cityName);
    
          fetch(`https://api.openweathermap.org/data/2.5/weather?q=`+this.state.cityName+`&appid=f3ee66722740d00cc6f197cbcab3d534`, {
            method: 'GET'
          }).then((response) => {
            return response.json();
          }).then((res) => {
            this.setState({
              currWeatherRes: res
            })
          });
      }
    
      handleChange = (event) => {
        this.setState({cityName:event.target.value});
      }
    
      render() {
        console.log(this.state.currWeatherRes)
        return (
          <div className="weather-app">
              <form onSubmit={this.handleSubmit}>
                <input type="text" value={this.state.cityName} onChange={this.handleChange} placeholder="Enter City"/>
                <button type="submit" value="Submit">Submit</button>
              </form>
              {(typeof this.state.currWeatherRes.main != "undefined") ? (
                  <div className="weather-details">
                      <div className="weather-location">
                          <div className="location">Loctaion: {this.state.currWeatherRes.name}</div>
                      </div>
                  </div>
              ):('')}
          </div>
        );
      }
    }
    
    export default App;
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      相关资源
      最近更新 更多