getApp()
The getApp() function is a function used to obtain app instances. Generally, there is no problem, but in several special scenarios it will bring you unexpected bugs.
Use in the onLaunch callback function in
// App({ onLaunch() { (getApp(), '!!'); } });
You will find that undefined will be output at this time, which is actually understandable. After all, it is still in the initialization stage and the app has not been born yet. If the code is just that simple, you can easily find this problem. Once you call a method in it and the method accidentally gets an app instance to get a variable, an accident occurs.
So~ If there is no synchronization requirement, you can call the function in onLaunch to wrap a layer of setTimout to avoid trapping:
// App({ onLaunch() { setTimeout(() => { // ... Call other functions }); } });
Assign getApp() to a variable
Let's create a file:
// const app = getApp(); export function checkVersion() { ('checked!'); ('app', app, '!!'); }
The above files generally won't encounter any problems, but once you introduce them in, the surprise will arise.
// import { checkVersion } from 'a'; App({ onLaunch() { ('I\'m Fine!'); }, onShow() { checkVersion(); } });
At this time, you will find that the app variable is undefined. This error may be difficult for you to detect, especially a general library encapsulated. It is usually good, but suddenly it is used in it, and it is hey.
So~ To avoid this problem, try to minimize the sharing of public app instances, but use getApp() directly in the method to get the instance object. If you want to use global variables, it would be better to store variables separately in a single js file, for example:
// export default { userInfo: null, isIos: false, isLaunched: false, };
// import store from 'globalStore'; App({ onLaunch() { = true; }, onShow() { const { isLaunched } = getApp().store, (isLaunched); }, store, });
This allows you to obtain global variables by importing modules, and it is also compatible with getting global variables through getApp().store.
But in principle, I still recommend reading and writing global variables by importing modules. After all, in some cases getApp() returns undefined .
Define variables at the top of the page entry file
It is common to define variables in page entry files, but you must note that the page entry file will only be executed once, not each page instance is independent, such as the following code:
// pages/page/ import { getDetailInfo } from 'api'; let ajaxLock = false; Page({ onLoad() { (); }, async getRemoteData() { if (ajaxLock) { return; } ajaxLock = true; try { await getDetailInfo(); } catch(err) { // ... Handling error } finally { ajaxLock = false; } }, });
The page logic is relatively simple. You request remote data as soon as you enter the page. There is no problem with visual inspection. However, once you open multiple pages at the same time, you will find that only the first page requests data, and the subsequent pages are not requested, because these pages share the ajaxLock variable, so you must pay attention to the usage scenarios of the variables declared at the top of the page.
Directly assign global variables in data in page entry file
Directly upload the code:
// pages/page/ Page({ data: { isIos: getApp()., }, });
// App({ onLaunch() { (); }, getSysInfo() { return new Promise((resolve, reject) => { ({ success: resolve, fail: reject, }); }).then((res) => { const { store } = getApp(); = () === 'ios'; }); }, store: { isIos: false, }, });
The main logic of the above code is to know whether the current device is ios. The code seems to be stable when running on the simulator, but once it is on the real machine, it will be good and bad, because the variable isIos does not obtain the state synchronously. Once the assignment is completed after the page entry function is executed, the state will be displayed incorrectly.
Therefore, for some states that are not synchronously assigned, do not operate directly by assigning data directly to initialization. It is best to put it in the onLoad callback function to assign states.
What you don't know () and ();
These two functions are also commonly used. They are mainly used to query a certain element and are used to deal with whether the element is in the visual area. The problems with these two functions are pure and cute. I only realized when I realized a special need. I was really aware of it, not aware of it, and it was terrifying to think about it carefully...
Let's reproduce the problem, and the page entry function is written like this:
// pages/page/ let index = 0 Page({ data: { tag: 0 }, onLoad() { if (index++ < 2) { ({ url: '/pages/page/index' }); } ({ tag: index },() => { setTimeout(() => { const { tag } = ; const query = (); // const query = (); (`.c-${ tag }`).boundingClientRect(); ((res) => { (tag, res); }); }, 2000); }); } });
<!-- Template file --> <view class="c-{{tag}}">demo</view>
I simulated the situation of opening multiple pages at the same time. In the developer tools, you will find that the result of the first two pages is actually null! ! ! At that time, I felt that the world was a little collapsed. So I suspect that it is a global function after all, so it querys the wxml under the currently active window. How to solve it? I looked through the official documents, searched for small characters with a magnifying glass, and found that there was this method. With a try-out attitude, the problem suddenly solved. Of course, the same problem is the same, so I won't make a demonstration.
So~ For good health, I highly recommend using and directly.
The above is the magic pit I have stepped on in developing WeChat mini programs in recent years. I hope you don’t step on it again~~
Summarize
This is the article about the pitfalls you may not have stepped on in WeChat mini program development. For more information about WeChat mini program development, please search for my previous articles or continue browsing the relevant articles below. I hope everyone will support me in the future!