Mini Program wx.request this.data

const app = getApp ()

Page ({
data: {

)
questions:{},

},
onLoad: function (options) {

this.requestTopic(this);

},
onReady: function () {
},
onShow: function () {

console.log(this.data);
console.log(this.data.questions);

},
requestTopic: (that) = >
{

var params = { action: "topics"};
wxApi.postRequest(app.globalData.serverUrl, params).then(
  (res) => {
    that.data.questions = res.data;
    //that.setData({ questions: res.data })
})

}

})

the code has been simplified. In onShow, console.log (this.data.questions); why can"t you get the value-_!

clipboard.png

Feb.28,2021

because the requestTopic is asynchronous, the onShow is finished, and the requestTopic callback has not yet been executed.


onShow executes before request returns, so when you print question in onShow, it must have no value.

so why is it worth printing question in data,data in onShow as well? Because the object printed by chrome does not simply print its current value, but a reference to the object, all changes you make to the object will be reflected in the previous print results.

A simple way to verify this is that you make a breakpoint in request, and when you execute to this breakpoint, you see if the data printed in onShow has a value. Then release the breakpoint and see if it's worth it. And then you'll understand.

Menu