收藏
回答

在wx.ChooseLocation的回调函数没法使用this.setData

我想写一个用地图查询位置并记录位置的页面,在js文件:

Page({

    data:{  //定义经纬度数据

lat:null

longi:null

}

......

findlc: function(event){  //页面组件出发函数,点击一个组件会调用本函数

.....

wx.chooseLocation({  //调用地图的查询位置功能

      success: function(res){

        // success

        console.log(res.name)   //这里可以正常获取位置数据

        console.log(res.address)

        console.log(res.latitude)

       this.setData({   //但在这里就会报错,说没有setData方法

lat: res.latitude

longi:res.longitude

})

      


      },

      fail: function() {

        // fail

      },

      complete: function() {

        // complete

      }

    })

}

})


在上面的findlc函数中,调用wx.chooseLocation,成功则回调success函数,此时this.setData()会报错,但是如果我把this.Data从wx.chooseLocation中移出到findlc函数下面,则可以正常运行,看现象,在wx.chooseLocation的回调函数中不能用this.setData来更新页面的初始数据。这是一个bug吗?

回答关注问题邀请回答
收藏

6 个回答

  • .
    .
    2022-01-19

    let that = this 就可以了 小心onshow 选完点回来会跑onshow 坑死我了

    2022-01-19
    有用
    回复
  • 阿水
    阿水
    2017-11-13
    onShow:function(){  
           var that = this;
           wx.getLocation({
               type: 'wgs84',
               success: function (res) {
                   var latitude = res.latitude
                   var longitude = res.longitude
                   var speed = res.speed
                   var accuracy = res.accuracy
                   lat = res.latitude;
                   lon = res.longitude;
                   console.log(res);
     
                   that.setData({
                       alert_text: '当前地址获取成功!',
                       alert_type:'red',
                   })
               },
               fail: function (res) {
                   // a();
               }
           })
       }

    加上var that = this之后可以运行了

    2017-11-13
    有用
    回复
  • Debugger
    Debugger
    2017-08-14

    为什么我用var that = this 还是不行啊

    2017-08-14
    有用
    回复
  • Rui
    Rui
    2017-02-06

        //       var page = getCurrentPages();

        //       page[page.length-1].setData({zzz:"sss"});


    2017-02-06
    有用
    回复
  • 雕哥
    雕哥
    2016-12-27

    我之前也是这样,后来才知道

    var that = this

    2016-12-27
    有用
    回复
  • kevin老孟
    kevin老孟
    2016-12-27

    靠,这个真是绕呀,涉及到了闭包(对我来说,这个很难理解),我用下面的方法刚刚成功解决了:

    findlc:function(event){

    //增加下面一行,把page对象赋予一个临时变量that,

    var that = this

    ......

      wx.chooseLocation({  //调用地图的查询位置功能

          success: function(res){

             

           that.setData({   //这样就不会报错了

               lat: res.latitude

               longi:res.longitude

            })

        }

     })

    }

    貌似这样可以避免success回调函数错把this认作自己,从而爆出上面提到的函数不存在错误。这里that明确指明是page对象了。


    希望大家不要和我踩同样坑。

    2016-12-27
    有用
    回复
登录 后发表内容