反应不立即显示当前状态

时间:2019-09-13 14:27:53

标签: reactjs api

我正在创建一个React / .NET应用程序,该应用程序对OpenWeather API进行API调用。用户键入他们当前所在的城市,然后按提交以接收温度,位置和天气摘要。 API调用和数据显示正常,并且一切正常。我想向用户展示是否是T恤衫天气,具体取决于温度是>还是<低于18摄氏度。我创建了一个“决策”状态以根据当前温度进行更新。这是我的代码:

import React, { Component } from "react";

export class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      temp: "",
      summary: "",
      city: "",
      location: "",
      decision: ""
    };
  }

  getData(e) {
    e.preventDefault();
    fetch("api/weather/city/" + this.state.location)
      .then(response => response.json())
      .then(data =>
        this.setState({
          temp: data.temp,
          summary: data.summary,
          city: data.city
        })
      );
  }

  isItSunny = async () => {
    if (Math.floor(this.state.temp) > 18.0) {
      this.setState({ decision: "Yes" });
    } else if (this.state.temp == "") {
      this.setState({ decision: "" });
    } else {
      this.setState({ decision: "No" });
    }
  };

  render() {
    return (
      <div>
        <center>
          <h1>Weather</h1>
          <p>Please enter your city:</p>
          <form
            onSubmit={e => {
              this.isItSunny();
              this.getData(e);
            }}
          >
            <input
              type="text"
              placeholder="Type city here..."
              value={this.state.location}
              onChange={e => this.setState({ location: e.target.value })}
            />
            <button type="submit">Submit</button>
          </form>
          <h4>City</h4>
          <p>{this.state.city}</p>
          <h4>Temperature</h4>
          <p> {this.state.temp}</p>
          <h4>Description</h4>
          <p> {this.state.summary}</p>
          <p>Is it T Shirt Weather: {this.state.decision}</p>
        </center>
      </div>
    );
  }
}

我的问题是,当我单击提交时,this.state.decision无法呈现。我必须再次单击提交以进行更新。在第一次提交时,它仍然认为this.state.decision == ""并非如此,现在应该是一个数字。

有人可以告诉我我该怎么做才能使代码在提交表格后立即识别出温度的更新状态吗?抱歉,我是React新手!

谢谢。

2 个答案:

答案 0 :(得分:3)

第一次单击submit时,this.state.temp始终是""的初始值。您应该渲染 decision,而不要保持其状态,因为它是从状态派生的:

  render() {

    let decision = "";
    if (Math.floor(this.state.temp) > 18.0) {
      decision = "Yes";
    } else if (this.state.temp == "") {
      decision = "";
    } else {
      decision = "No";
    }     

    return (
      <div>
        <center>
          <h1>Weather</h1>
          <p>Please enter your city:</p>
          <form
            onSubmit={e => {
              this.isItSunny();
              this.getData(e);
            }}
          >
            <input
              type="text"
              placeholder="Type city here..."
              value={this.state.location}
              onChange={e => this.setState({ location: e.target.value })}
            />
            <button type="submit">Submit</button>
          </form>
          <h4>City</h4>
          <p>{this.state.city}</p>
          <h4>Temperature</h4>
          <p> {this.state.temp}</p>
          <h4>Description</h4>
          <p> {this.state.summary}</p>
          <p>Is it T Shirt Weather: {decision}</p>
        </center>
      </div>
    );
  }

此代码可以改进,但可以为您提供帮助。您无需保持decision的状态,因为您可以从已经拥有的状态进行计算。

答案 1 :(得分:0)

让我们调试代码。您首先调用了this.isItSunny()函数。因此,转到该函数并找到城市的初始温度为""。因此this.setState({decision:""})将在此处暂停。然后转到this.getData(e)函数并设置temp:{value}。之后,它将设置this.setState({decision:""})。这是问题所在。因为它不会再次检查条件。您只需从

删除this.isItSunny()函数就可以执行相同的操作
<form
      onSubmit={e => {
      //this.isItSunny();
      this.getData(e);
   }}
>

然后在this.isItSunny()函数中设置值后添加this.getData(e)函数。这是this.getData(e)函数的代码:

async getData(e) {
    const response = await fetch("api/weather/city/" + this.state.location);
    const data= await response.json();
    await this.setState({ temp: data.temp,
          summary: data.summary,
          city: data.city });
    this.isItSunny();
}