Javascript 这件事的背景很混乱——我做错了什么?
你能看看我的密码吗?我知道问题与此上下文有关,但我不确定我做错了什么,与getLocationInfo函数有关。我在构造函数中放了一个bind语句,但我也用一个arrow函数编写了函数定义(我认为它有隐式绑定?)。如果注释掉bind语句,则会得到“getLocationInfo未定义”。如果我像这样写出函数Javascript 这件事的背景很混乱——我做错了什么?,javascript,reactjs,geolocation,Javascript,Reactjs,Geolocation,你能看看我的密码吗?我知道问题与此上下文有关,但我不确定我做错了什么,与getLocationInfo函数有关。我在构造函数中放了一个bind语句,但我也用一个arrow函数编写了函数定义(我认为它有隐式绑定?)。如果注释掉bind语句,则会得到“getLocationInfo未定义”。如果我像这样写出函数 getLocationInfo(position){ *insert function* } 。。。我得到了一个意外的标记错误,但是所有的花括号都正确地关闭了 感谢您的指导。。。请
getLocationInfo(position){
*insert function*
}
。。。我得到了一个意外的标记错误,但是所有的花括号都正确地关闭了
感谢您的指导。。。请参阅下面的代码
class App extends Component {
constructor(props){
super(props)
this.state = {
fahrenheit: "",
celsius: "",
image: "",
description: "",
location: ""
}
this.getLocationInfo = this.getLocationInfo.bind(this)
}
componentDidMount() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getLocationInfo);
} else {
alert("Geolocation is not supported by this browser.");
}
getLocationInfo = (position) => {
axios.get(`http request info`)
.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
})
})
}
}
尝试
.getCurrentPosition(this.getLocationInfo)代码>。您需要使用类方法。。akanavigator.geolocation.getCurrentPosition(this.getLocationInfo)
。。。另外,您没有使用回调中的位置,那么为什么要使用navigator呢?看起来您可能缺少componentDidMount
上的右括号,因此getLocationInfo
实际上是在componentDidMount
的主体中定义的