Cannot read property 'globalData' of null;微信小程序

Cannot read property 'globalData' of null;

    • Cannot read property 'globalData' of null;
      • 1.报错:Cannot read property 'globalData' of null;
      • 2.错误分析:
      • 3.解决方法:
      • 4.样例

Cannot read property ‘globalData’ of null;

1.报错:Cannot read property ‘globalData’ of null;

2.错误分析:

这个报错的原因可能是this的指向不明确,导致在设置或者获取页面变量或者全局变量的时候出现

3.解决方法:

在页面定义方法的时候,第一步先声明一个变量var that=this

将页面的指针先赋值给that,然后在函数中使用判断,或者循环,或者对象的时候获取变量直接为that.data获取。

如果是获取全局变量的话就可以先在页面第一行声明var app = getApp()
方法中获取全局变量直接使用app.globalData.userInfo来获取

4.样例

先在index.js中定义一个pwdInput方法,页面的话可以直接在index.wxml中添加一个input框,绑定pwdInput这个方法就行

var app = getApp()
page({
data: {
    phone: '',
    password: '',
    phoneTest:'18119999999'
  },
pwdInput: function (e) {
    var that=this
    this.setData({//这一行的this也可以换成that
      password: e.detail.value,
      phone:that.data.phoneTest //这里不能使用this
    })
    wx.sendSocketMessage({
		data:that.data.password  //这里不能使用this,因为this指向了当前的sendSocketMessage里面的对象
   })
   //获取全局变量
   let gPhone = app.globalData.userPhone
   //设置全局变量
   app.globalData.userPwd = this.data.password //这里this可以换成that
}
  })

你可能感兴趣的:(小程序,微信,小程序)