日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

小程序 onLaunch 與 onLoad 異步問題的解決方案

作者:ZionHH 更新時間: 2022-05-12 編程語言

在小程序中,我們一般在onLaunch中發起登錄請求,由于是請求是異步的,在onLoad之后才執行完登錄請求,如果在onLoad中需要使用請求后的數據,會發現取不到值,以下是一些解決方式,可以按自己所需使用。

  1. 使用回調函數
// app.js
onLaunch () {
	wx.login({
		success: result => {
			wx.request({
				url: 'test.php' // 示例
				data: {...},
				success: res => {
					this.globalData.openId = res.data.openId
					 // 回調
					if (this.loginCallback) this.loginCallback(res.data)
				},
				fail: err => {
					// 需要的話請求失敗處也可以使用回調
				}
			})
		}
	})
}
// page.js
onLoad () {
	const app = getApp()
	if (app.globalData.openId) {
		// do something
	} else {
		app.loginCallback = (data) => {
			// do something
		}
	}
}
  1. 使用Promise
// app.js
App({
	initLogin () {
		return new Promise((resolve, reject) => {
			wx.login({
				success: result => {
					wx.request({
						url: 'test.php' // 示例
						data: {...},
						success: res => {
							resolve(res.data)
						},
						fail: err => {
							reject('error')
						}
					})
				}
			})
		})
	}
})
// page.js
onLoad () {
	const app = getApp()
	app.initLogin().then(res => {
		// do something
	}).catch(err => {})
}
  1. 使用Object.defineProperty監聽
// app.js
watch (method) {
	let obj = this.globalData
	// 這里監聽 openId
	Object.defineProperty(obj, "openId", {
		configurable: true,
		enumerable: true,
		set: function (value) {
			method(value);
		},
		get: function () {
			return this.globalData
		}
	})
}
onLaunch () {
	wx.login({
		success: result => {
			wx.request({
				url: 'test.php' // 示例
				data: {...},
				success: res => {
					this.globalData.openId = res.data.openId
				}
			})
		}
	})
}
// page.js
onLoad () {
	const app = getApp()
	app.watch(this.watchBack)
}
watchBack (openId) {
	if (openId) {
		// do something
	}
}
  1. 使用getCurrentPages
// app.js
onLaunch () {
	wx.login({
		success: result => {
			wx.request({
				url: 'test.php' // 示例
				data: {...},
				success: res => {
					const currentPage = wx.getCurrentPages()[0]
					// 觸發當前頁的init方法
					currentPage.init(res.data)
				}
			})
		}
	})
}
// page.js
init (data) {
	// do somethine
}
  1. reLaunch重載頁面
// app.js
onLaunch () {
	wx.login({
		success: result => {
			wx.request({
				url: 'test.php' // 示例
				data: {...},
				success: res => {
					// 請求結果存到了storage里,再跳到頁面可以獲取到storage里的數據
					wx.reLaunch({
						url: '/pages/n-index/n-index',
					})
				}
			})
		}
	})
}
  1. 設置啟動頁

你有什么更完美的解決方法,快在下方評論一起討論吧。

原文鏈接:https://blog.csdn.net/z291493823/article/details/121215584

欄目分類
最近更新