reactjs - 使用 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}
解决方案
使 inputValue 成为状态的一部分。没有理由将它作为这样的组件之外的全局变量保留。
推荐阅读
- javascript - 从 csv 文件中遍历头数组以获取 P5.js 中的下拉列表
- php - LARAVEL - 表单验证返回查看而不是返回 JSON?
- java - 谁能告诉我这个错误的原因?
- go - 在 Script 部分的 .gitlab-ci.yml 中调用 GO 二进制文件并捕获响应
- python - 字符串格式化 Python 练习题 - LearnPython
- reactjs - 如何在 Material UI 中覆盖 Drawer
- machine-learning - 如何在pytorch多类问题的交叉熵损失中设置目标
- python - 将透明图像合并到另一个背景
- firebase - 如何让 StreamBuilder 停止监听事件
- javascript - 当用户滚动到该部分时,如何使用 JS(无库)激活 CSS 动画?