美文网首页小程序
小程序onLaunch和onLoad

小程序onLaunch和onLoad

作者: 风雪夜丶 | 来源:发表于2019-05-31 12:00 被阅读0次

onLaunch和onLoad是异步的,当小程序启动时触发onLaunch,但是同时也在触发所进入页面的onLoad,所以会造成进去页面时在onLoad里不会拿到由onLaunch获取的值,
解决方法:
在app.js中的onLaunch中调取接口获取到值

        // 此处请求封装过
        app.request('url',data).then(res => {
            this.globalData.resData = res
            // 此处判断app对象中有没有这个回调函数
            if (this.CallbackFn) {
                // 如果有说明,onLoad中没有拿到值,把结果当参数再传入回调中
                this.CallbackFn(res);
            }
        }).catch(err => {
            wx.showToast({
                title: err.Message,
                icon: 'none'
            });
        })

在进入的页面中的onLoad中

        if (app.globalData.resData && app.globalData.resData != '') {
            // 如果有值,说明接口已经返回,所以直接赋值使用
            this.setData({
                resData : resData 
            })
        } else {
            //如果没有,给app定义一个回调,拿到接口返回参数
            app.CallbackFn= data=> {
                if (data!= '') {
                    that.setData({
                        resData: data
                    })
                }
            }
        }

相关文章

网友评论

    本文标题:小程序onLaunch和onLoad

    本文链接:https://www.haomeiwen.com/subject/utdwtctx.html