首页 > 解决方案 > 使用 Axios 在天气应用程序链接中插入变量

问题描述

我正在使用天气应用程序 API 创建天气应用程序。如果我在给定的链接中对国家进行硬编码,我就能达到可以打印天气的程度。我的目标是: 1 - 当我在输入中写入城市的值并获取值并将其插入链接时打印城市的值。2 - 不幸的是我不能这样做[我达到的目的是我可以获得输入,但它不会在链接中接受它]

提示:我是一名 React 初学者,并尽我最大的努力使我的代码工作并使用 DRY 原则。

感谢您的宝贵时间,并可以在这里使用您的帮助。提前致谢。

//Importing
import React, { Component } from "react";
import axios from "axios";
//syntax

let inputValue = "";
console.log(" input value before updated", inputValue);
export default class main extends Component {
  state = {
    showList: false,
    data: "",
    temp: "",
    feels_like: "",
    humidity: "",
    pressure: "",
    name: "",
    country: "",
    description: "",
    icon: "",
    weather: "",
  };
  //Component Did mount

  handleInput = (event) => {
    this.setState({
      data: event.target.value,
    });
  };
  submitted = () => {
    inputValue = this.state.data;
    const show = this.state.showList;
    this.setState({ showList: !show });
  };

  componentDidMount() {
    axios
      .get(
        `http://api.openweathermap.org/data/2.5/weather?q=${inputValue},uk&APPID=xxxxxxxxxxxxxxxxx`
      )
      .then((response) => {
        this.setState({
          temp: response.data.main.temp,
          feels_like: response.data.main.feels_like,
          humidity: response.data.main.humidity,
          pressure: response.data.main.pressure,
          name: response.data.name,
          country: response.data.sys.country,
          description: response.data.weather[0].description,
          icon: response.data.weather[0].icon,
          weather: response.data.weather[0].main,
        });
      })
      .catch((error) => console.log(error));
  }

  render() {
    let feels_like = this.state.feels_like;
    let temp = this.state.temp;
    let humidity = this.state.humidity;
    let pressure = this.state.pressure;
    let name = this.state.name;
    let country = this.state.country;
    let description = this.state.description;
    let icon = this.state.icon;
    let weather = this.state.weather;
    let list = null;
    if (this.state.showList) {
      list = (
        <div>
          <h1>{this.state.data}</h1>
          <h1>{feels_like}</h1>
          <h1>{temp}</h1>
          <h1>{humidity}</h1>
          <h1>{pressure}</h1>
          <h1>{name}</h1>
          <h1>{country}</h1>
          <h1>{description}</h1>
          <img
            alt=""
            src={`http://openweathermap.org/img/wn/${icon}.png`}
          ></img>
          <h1>{weather}</h1>
        </div>
      );
    }
    return (
      <div>
        <input
          onChange={this.handleInput}
          typw="text"
          placeholder="Enter a country name"
        />
        <button onClick={this.submitted}>Search</button>
        {list}
      </div>
    );
  }
}

额外信息:

.get(
        `http://api.openweathermap.org/data/2.5/weather?q=${inputValue},uk&APPID=xxxxxxxxxxxxxxxxx`
      )

这是我得到 404 的部分,因为它不接受${inputValue}

标签: reactjsapiaxios

解决方案


使 inputValue 成为状态的一部分。没有理由将它作为这样的组件之外的全局变量保留。


推荐阅读