[英]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.