[英]How do I get Geolocation API co-ordinates out of my nested function and into React state?
[英]How can I get geolocation information saved to my local state?
我正在尝试创建一个天气应用程序,该应用程序根据您的地理位置告诉您天气情况。 我的意图是获取地理位置信息并将其设置为状态,但是我在下面的代码中遇到的错误是“无法读取null的setState属性”。 地理位置信息可以在我的控制台中很好地返回,因此检索信息不是问题。 我猜想它可能与范围有关? 试图想出一种替代方法来将此信息放置在我的本地州。 我使用state上的项目在我的JSX中进行渲染,但是认为没有必要将JSX留在其中。 有什么想法或启发?
class App extends Component {
constructor(){
super()
this.state = {
fahrenheit: "",
celsius: "",
image: "",
description: "",
location: ""
}
}
componentDidMount() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getLocationInfo);
} else {
alert("Geolocation is not supported by this browser.");
}
function getLocationInfo(position) {
axios.get(`http request info here`)
.then(response => {
this.setState({
description: response.data.weather[0].description
fahrenheit: response.data.main.temp,
image: response.data.weather[0].icon,
location: response.data.main.name
})
})
}
}
要使用setState
,必须使用类方法,这是一个在其定义中没有function关键字的函数。 您当前的错误来自此关键字具有不同的上下文。
class App extends Component {
constructor(props){
super(props)
this.state = {
fahrenheit: "",
celsius: "",
image: "",
description: "",
location: ""
}
}
componentDidMount() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getLocationInfo);
} else {
alert("Geolocation is not supported by this browser.");
}
getLocationInfo(position) {
axios.get(`http request info here`)
.then(response => {
this.setState({
description: response.data.weather[0].description
fahrenheit: response.data.main.temp,
image: response.data.weather[0].icon,
location: response.data.main.name
})
})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.