【问题标题】:Axios fetch in reactAxios 获取响应
【发布时间】:2017-03-28 15:32:36
【问题描述】:

在我的 react 应用程序中使用 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);
 }
}

但我最终得到了错误Uncaught TypeError: Cannot set property 'serverRequest' of undefined

【问题讨论】:

    标签: javascript reactjs axios


    【解决方案1】:

    success 被作为回调调用时,它的this 值将不正确 - 在你的情况下它是undefined。您可以通过在回调函数上使用 bind 来解决此问题:

    navigator.geolocation.getCurrentPosition(success.bind(this), error);
    

    【讨论】:

    • 你成就了我的一天。谢谢!
    猜你喜欢
    • 2020-08-10
    • 2021-07-27
    • 2019-09-07
    • 1970-01-01
    • 2021-01-31
    • 2023-01-12
    • 1970-01-01
    • 2018-09-14
    • 2020-03-22
    相关资源
    最近更新 更多