程序在加载时候,从云数据库读取用户信息,然后使用this.setData()给view里面的东西赋值。但是赋值之后不起作用,而且this.setData()后面的console也不执行了。
// miniprogram/pages/index/index.html.jslet app = getApp();const db = wx.cloud.database();Page({ /** * 页面的初始数据 */ data: { name:'', grade: '' }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.onGetOpenid(); }, onGetOpenid() { // 调用云函数 wx.cloud.callFunction({ name: 'login', data: {}, success: res => { this.onInit(res.result.openid); }, fail: err => { console.error('[云函数] [login] 调用失败', err) } }); }, onInit(openid) { // console.log(openid); // console.log(typeof (openid)); //初始化用户信息 db.collection('user') .where({ _openId: openid //填入用户当前openId }).get({ success: function (res) { // console.log(res.data); if (res.data.length > 0) { console.log("用户已存在"); console.log("res: ", res); //获取用户的stuId app.globalData.stuId = res.data[0].stuId; app.globalData.score = res.data[0].score; app.globalData.name = res.data[0].name; this.setData({ name:app.globalData.name, grade:app.globalData.score }); console.log("app.globalData.stuId", app.globalData.stuId); console.log("app.globalData.score", app.globalData.score); console.log("app.globalData.name", app.globalData.name); } else { console.log('用户不存在,请先注册') wx.redirectTo({ url: '../register/register', }); } }, err: function (e) { console.error('初始话用户信息失败', err) } }) } }) |
代码定位:54行-58行
请问代码有什么问题吗,应该怎么解决。
非常感谢各位!!!!

onInit(openid) {varthat =this;db.collection('user').where({_openId: openid//填入用户当前openId}).get({success:function(res) {if(res.data.length > 0) {that.setData({name:app.globalData.name,grade:app.globalData.score});}else{console.log('用户不存在,请先注册')wx.redirectTo({url:'../register/register',});}}})}类似这样,异步需要存this
this作用域有问题,使用箭头函数即可
this.setData 的指向不对, var _this =this
报什么错
你这个不报错吗
let that = this
db.collection('user')
that.setData 云开发不用这样的吗 不然不会报错吗