Javascript can print out objects, but sub-objects can't get them.

specifically, the onload () method assigns values to page variables in Mini Program. The code is as follows:

  onLoad() { 
    console.log("all", app.globalData);
    console.log("app", app.globalData.appinfo.client_id);
    console.log("user", app.globalData.userinfo);

    this.setData({
      nickName: app.globalData.userinfo.nickName,
      avatarUrl: app.globalData.userinfo.avatarUrl
    });
  }

the screenshot printed out is:

Why can"t userinfo get it?


console is asynchronous, that is, when you press the object arrow, the data will be requested again, so userinfo exists when you click on it, but when you get it on the page, there is actually data acquisition delay . If you set the settimeout delay of 3 seconds to get it, you should be able to get it.
I have encountered this problem before. The final solution is not to get the data in the page js, but to use a js under utils to obtain the data , and to return a method , then adjust this method when the page onload, and then assign the returned value to the page data , and then take the value directly on the page. If you have to process the data, It is recommended that declare functions in the wxs file to deal with . There will be data delays in the page js.
for example:
for example, the data of my shopping cart needs to change in real time, so I wrote a shopping-cart.js file under utils, and sc is all the data needed for the page contained in the shopping cart

clipboard.png

sc
clipboard.png

clipboard.png

clipboard.png

wxs;

clipboard.png


you didn't call the API to get userinfo

Menu