Javascript Axios进站反应
我需要一些助手在我的react应用程序中使用Axios。我将它与地理定位结合使用以获取用户位置,并在Axios的api调用中使用它 我的代码是:Javascript Axios进站反应,javascript,reactjs,axios,Javascript,Reactjs,Axios,我需要一些助手在我的react应用程序中使用Axios。我将它与地理定位结合使用以获取用户位置,并在Axios的api调用中使用它 我的代码是: componentDidMount() { if (navigator.geolocation){ function success(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude;
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);
}
}
但是我最终得到了错误
uncaughttypeerror:cannotsetproperty'serverRequest'of undefined
当success
被调用为回调时,它的这个
值将不正确-在您的情况下,它是undefined
。您可以通过在回调函数上使用bind
来修复此问题:
navigator.geolocation.getCurrentPosition(success.bind(this), error);
你让我高兴极了。谢谢