Axios 在反应中获取
Axios fetch in react
我需要一些帮助才能在我的 React 应用程序中使用 Axios。我将它与地理定位结合使用来获取用户位置,并在 api 与 Axios 的调用中使用它。
我的代码是:
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);
}
}
但我最终遇到错误 Uncaught TypeError: Cannot set property 'serverRequest' of undefined
当 success
作为回调调用时,其 this
值将不正确 - 在您的情况下为 undefined
。您可以通过在回调函数上使用 bind
来解决此问题:
navigator.geolocation.getCurrentPosition(success.bind(this), error);
我需要一些帮助才能在我的 React 应用程序中使用 Axios。我将它与地理定位结合使用来获取用户位置,并在 api 与 Axios 的调用中使用它。
我的代码是:
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);
}
}
但我最终遇到错误 Uncaught TypeError: Cannot set property 'serverRequest' of undefined
当 success
作为回调调用时,其 this
值将不正确 - 在您的情况下为 undefined
。您可以通过在回调函数上使用 bind
来解决此问题:
navigator.geolocation.getCurrentPosition(success.bind(this), error);