fri*_*sk0 2 javascript reactjs axios
我需要一些帮助在我的反应应用程序中使用Axios.我将它与地理位置结合使用以获取用户位置并在与Axios的api调用中使用它.
我的代码是:
componentDidMount() {
if (navigator.geolocation){
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var th = this;
this.serverRequest =
axios.get(`https://api.darksky.net/forecast/APIKEY/`+latitude+`,`+longitude+`?units=auto`)
.then(result => {
th.setState({
daily: result.data.daily.data,
loading: false,
error: null
});
})
.catch(err => {
// Something went wrong. Save the error in state and re-render.
this.setState({
loading: false,
error: err
});
});
};
function error() {
console.log( 'geolocation error' )
};
navigator.geolocation.getCurrentPosition(success, error);
}
}
Run Code Online (Sandbox Code Playgroud)
但我最终得到了错误 Uncaught TypeError: Cannot set property 'serverRequest' of undefined
当success被称为回调时,它的this值将不正确 - 在你的情况下它是undefined.您可以通过bind在回调函数上使用来解决此问题:
navigator.geolocation.getCurrentPosition(success.bind(this), error);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
608 次 |
| 最近记录: |