【发布时间】:2020-05-08 02:34:26
【问题描述】:
我有这个从浏览器导航器功能到天气 api 的简单获取位置。我不明白为什么纬度和经度的控制台都可以工作,但是当我执行 setState 时,它对我大喊大叫说未捕获TypeError: Cannot read property 'setState' of undefined.
为了更清楚这两个控制台,我得到了位置
console.log(position.coords.latitude)
console.log(position.coords.longitude)
但这是说不能将未定义的东西传递给 setState
this.setState({lat:position.coords.latitude,lon:position.coords.longitude})
import React from 'react';
import axios from 'axios';
import WeatherGadget from './weather.component'
export default class WeatherApi extends React.Component {
constructor(props) {
super(props);
this.state = { city: null,lat:0,lon:0,wind:0,weather:0,icon:null };
}
componentDidMount() {
const location = ()=>{navigator.geolocation.getCurrentPosition(function(position) {
console.log(position.coords.latitude)
console.log(position.coords.longitude)
this.setState({lat:position.coords.latitude,lon:position.coords.longitude})
//Uncaught TypeError: Cannot read property 'setState' of undefined
})}
location();
const url = `https://api.openweathermap.org/data/2.5/onecall?lat=${this.state.lat}&lon=${this.state.lon}&appid=8821HIDDEN4e9d78`;
const getWeather = async ()=>{
let res = await axios.get(url)
const weatherObj = res.data;
console.log("===",weatherObj)
const currentWeather = weatherObj.current.temp
const windSpeed = weatherObj.current.wind_speed
const icon = weatherObj.current.weather[0].icon
this.setState({wind:windSpeed,weather:currentWeather,icon:icon})
}
getWeather()
}
render() {
return (
<div >
<WeatherGadget city={this.state.city} wind ={this.state.wind} weather={this.state.weather} icon={this.state.icon}/>
</div>
)
}
}
【问题讨论】:
-
该代码块中的 this 与组件范围的 this 不同。尝试在 getCurrentPosition 中使用函数并将其绑定到构造函数中。
-
对
getCurrentPosition(function(position)使用箭头函数或将其绑定到function(position) -
像这样:
()=>{navigator.geolocation.getCurrentPosition((position) =>{
标签: javascript reactjs react-native react-redux geolocation