无法按 IP 获取用户位置详细信息



你好,我是反应的新手,并试图建立一个天气网站。 我有一个有效的搜索功能,但我也试图为用户获取当地天气。

为此,我从以下位置获得城市: https://geoip-db.com/json/

天气 API:https://api.openweathermap.org/data/2.5/

然后,我将该城市另存为状态中的变量,以便我可以在 API 中使用它。

这是代码: `

state = {
geoipCity: "",
}
componentDidMount(){
const geoApiUrl = "https://geoip-db.com/json/";
fetch(geoApiUrl)
.then(res => res.json())
.then(geoip => {
this.setState({ geoipCity: geoip.city })
})
.catch(err => {
console.log("Fetch error: " + err);
});
console.log("prefetch:" + this.state.geoipCity)
const weatherApiUrl = `${api.base}weather?q=${this.state.geoipCity}&weather&units=metric&APPID=${api.key}`;
fetch(weatherApiUrl)
.then(res => res.json())
.then(result => {
console.log(result)
let locationOutput = document.querySelector("#locationOutput");
if(result.cod === "404"){
locationOutput.innerHTML = `${this.state.geoipCity} is not a valid city name`;
}
/*
locationOutput.innerHTML = `
Your live in ${this.state.geoipCity} and it feels like ${result.main.feels_like}°C`;
*/
})
.catch(err => {
console.log("Fetch error: " + err);
});   
}

'

因此,第一次获取获取城市并将其保存在GeoipCity状态变量中。 我尝试在 API 搜索中使用它。 但是在此之前,我有:

console.log("prefetch:" + this.state.geoipCity)

这告诉我this.state.geoipCity是空的。

有什么想法吗?

编辑:已解决,这是代码,以防将来有人从中受益

'

componentDidMount(){
const geoApiUrl = "https://geoip-db.com/json/";
fetch(geoApiUrl)
.then(res => res.json())
.then(result => {
console.log(result)
this.setState({ geoipCity: result.city }, () => {
//console.log(this.state);
const weatherApiUrl = `${api.base}weather?q=${this.state.geoipCity}&weather&units=metric&APPID=${api.key}`;
fetch(weatherApiUrl)
.then(res => res.json())
.then(result => {
console.log(result)
let locationOutput = document.querySelector("#locationOutput");
if(result.cod === "404"){
locationOutput.innerHTML = `${this.state.geoipCity} is not a valid city name`;
}

locationOutput.innerHTML = `
Your live in ${this.state.geoipCity} and it feels like ${result.main.feels_like}°C`;
})
.catch(err => {
console.log("Fetch error: " + err);
});
});
//this.setState({ geoipCity: geoip.city })
})
.catch(err => {
console.log("Fetch error: " + err);
});
}

'

this.setState是异步的。

您需要使用 setState 的回调来控制台.log新状态。

this.setState({ geoipCity: geoip.city }, (newState) => {
console.log(newState);
});

每个setState都会重新渲染组件,但componentDidMount仅在第一次渲染时执行。

最新更新