[英]How can I change this axios API request into a fetch() function for a React app?
这是我为 API 调用 axios 的代码,我必须将其迁移到 fetch() function:
handleClick = e => {
axios
.post(
"https://api.openweathermap.org/data/2.5/weather?q=" +
this.state.term +
"&units=metric&appid=" +
API_KEY
)
.then(res => {
this.setState({
city_name: res.data.name,
temp: res.data.main.temp,
humidty: res.data.main.humidity,
wind: res.data.wind.speed,
weather_status: res.data.weather[0].main,
weather_desc: res.data.weather[0].description,
weather_icon: res.data.weather[0].icon
});
})//error logging
.catch(error => {
console.log(error);
});
};
render() {
return (
<div className="container">
<h1 className="header">Task 14 - Level 2</h1>
<Form onChange={this.handleChange} onClick={this.handleClick} />
<WeatherApp data={this.state} />
<div className="img"></div>
</div>
);
}
}
如何将 axios 调用更改为 fetch() function?
这是 fetch 中的等价物。
const handleClick = () => {
fetch( "https://api.openweathermap.org/data/2.5/weather?q=" +
this.state.term +
"&units=metric&appid=" +
API_KEY,{ method: 'POST' }). then( res => res.json())
.then( res => {
this.setState({
city_name: res.data.name,
temp: res.data.main.temp,
humidty: res.data.main.humidity,
wind: res.data.wind.speed,
weather_status: res.data.weather[0].main,
weather_desc: res.data.weather[0].description,
weather_icon: res.data.weather[0].icon
});
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.