Reactjs 使用Axios在天气应用程序链接中插入变量
早上好,节日快乐 我正在使用天气应用程序API创建天气应用程序。 如果我在给定的链接中硬编码国家,我就可以打印天气。 我的目标是: 1-打印城市的值,当我将其写入输入时,获取该值并将其插入链接。 2-不幸的是,我无法做到这一点[我达到的目的是我可以得到输入,但它不会在链接中接受它] 提示:我是一个React初学者,尽我最大的努力使我的代码工作,并使用DRY原则 我感谢你的时间,我需要你的帮助。 提前谢谢Reactjs 使用Axios在天气应用程序链接中插入变量,reactjs,api,axios,Reactjs,Api,Axios,早上好,节日快乐 我正在使用天气应用程序API创建天气应用程序。 如果我在给定的链接中硬编码国家,我就可以打印天气。 我的目标是: 1-打印城市的值,当我将其写入输入时,获取该值并将其插入链接。 2-不幸的是,我无法做到这一点[我达到的目的是我可以得到输入,但它不会在链接中接受它] 提示:我是一个React初学者,尽我最大的努力使我的代码工作,并使用DRY原则 我感谢你的时间,我需要你的帮助。 提前谢谢 //Importing import React, { Component } from &
//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>
);
}
}
这是我得到404的部分,因为它不接受
${inputValue}
使inputValue成为状态的一部分。没有理由将其作为全局变量保留在组件之外。感谢您的回复,我现在尝试了这个,但也不起作用。用两种方法解决了它。1-我将它们合并到一个函数下,因此我删除了安装的组件。2-我错误地保留了英国,因此每当我插入一个值(例如Tokyo)时,它将是不存在的英国东京。但若你们有任何解决方法的建议,我愿意继续安装组件。
.get(
`http://api.openweathermap.org/data/2.5/weather?q=${inputValue},uk&APPID=xxxxxxxxxxxxxxxxx`
)