我正在尝试创建一个天气应用程序,该应用程序根据您的地理位置告诉您天气情况。我的意图是获取地理位置信息并将其设置为状态,但是我在下面的代码中遇到的错误是“无法读取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
})
})
}
}
答案 0 :(得分:0)
要使用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
})
})
}
}