微信小程序app.getUserInfo(function(userInfo){ that.setData({ userInfo:userInfo }) })这么写哪错了
时间: 2023-02-16 14:47:02 浏览: 85
这段代码没有明显的错误,但是需要注意以下几点:
1. 在小程序的配置文件中需要配置用户信息获取的权限。
2. 如果在页面的 onLoad 函数中调用这段代码,需要确保在获取用户信息之前已经进行过登录操作。
3. 如果使用了 this.setData({...}) 来更新页面数据,需要在该页面的 data 中定义 userInfo 变量。
4. 如果这段代码在页面的 JS 文件中,需要确保在使用 this 之前已经绑定 this 到当前页面对象。
相关问题
const app =getApp() Page({ data: { }, onShow(){ this.setData({ userInfo:app.globalData.userInfo }) }, onLoad: function (options) { }, toMyOrder(){ wx.navigateTo({ url: '/pages/me/myOders/myOrders', }) }, login(){ wx.getUserProfile({ desc: '用于完善用户信息', }) .then(res=>{ console.log(res) this.setData({ userInfo:res.userInfo }) wx.cloud.database().collection('shop_users') .where({ _openid:app.globalData.openid }) .get() .then(result=>{ console.log(result) if(result.data.length == 0){ //添加用户数据到数据库 wx.cloud.database().collection('shop_users') .add({ data:{ avatarUrl:res.userInfo.avatarUrl, nickName: res.userInfo.nickName } }) .then(addResult=>{ console.log(addResult) //获取数据库用户信息 app.getUserInfo() wx.showToast({ title: '登录成功', }) }) }else{ wx.cloud.database().collection('shop_users') .doc(result.data[0]._id) .update({ data:{ avatarUrl:res.userInfo.avatarUrl, nickName: res.userInfo.nickName } }) .then(updateResult=>{ console.log(updateResult) //获取数据库用户信息 app.getUserInfo() wx.showToast({ title: '登录成功', }) }) } }) }) }, loinOut(){ app.globalData.userInfo = null wx.setStorageSync('userInfo', null) this.setData({ userInfo:null })
这段代码是一个小程序中的页面代码,其中主要实现了以下功能:
1. 在页面显示时,将全局变量 app.globalData.userInfo 中的用户信息赋值给页面的 data 中的 userInfo 变量。
2. 点击“我的订单”按钮时,跳转到“我的订单”页面。
3. 点击“登录”按钮时,调用 wx.getUserProfile 接口获取用户的头像和昵称等信息,并将其保存到数据库中。如果该用户已经存在于数据库中,则更新其信息。
4. 点击“退出登录”按钮时,将全局变量 app.globalData.userInfo 和本地存储中的 userInfo 变量都设为 null,并将页面的 userInfo 变量也设为 null。
总体来说,这段代码实现了一个小程序中常见的用户登录、退出登录和跳转页面等功能。
微信小程序授权登录怎么写代码
以下是微信小程序授权登录的示例代码:
1. 在app.js中定义全局变量
```
App({
globalData: {
userInfo: null
}
})
```
2. 在需要授权登录的页面中,引入wx.getUserInfo()方法
```
//index.js
const app = getApp()
Page({
data: {
userInfo: null
},
onLoad: function () {
// 在页面加载时判断用户是否已经授权登录
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo
})
} else {
// 如果用户未授权登录,则调用wx.getUserInfo()方法
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
this.setData({
userInfo: res.userInfo
})
}
})
}
}
})
```
3. 在需要显示用户信息的地方,使用data中的userInfo变量
```
<!-- index.wxml -->
<view wx:if="{{userInfo}}">
<image src="{{userInfo.avatarUrl}}" />
<text>{{userInfo.nickName}}</text>
</view>
```
以上代码是一个简单的微信小程序授权登录示例,你可以根据自己的需求进行修改和扩展。