1. Source of inspiration
More than once this week, the selector option was blank due to the long request time of the regional interface, and a new plan was formulated for this.
Original: Region requests to obtain all region information, such as obtaining a region tree with all the information of a province, city, and district at one time.
Now: Region requests to obtain sub-array information according to the parent id, such as passing the province id to obtain all city data in the province
After changing to a new solution, I found that every time I enter some pages, I need to load 3 or 4 regional interfaces, and they will be loaded repeatedly. However, the frequency of updating regional data is very low, so I thought that if I use data cache to replace the interface Is it okay to request?
2. Program practice
1. Flow chart
2. Detailed code
// 封装到hooks中
// 封装的请求
import {
http } from '../serve/qzf-http';
// 缓存
const villagesMap = new Map();
// 最大缓存时间
const maxVillagesTime = 1000 * 60 * 10;
// 分片请求地域加上缓存
export const initCacheVillages = (townId) => {
return new Promise((resolve, reject) => {
if (villagesMap.has('time') && Date.now() - villagesMap.get('time') > maxVillagesTime) {
villagesMap.clear();
}
if (villagesMap.has(townId)) {
// 命中
resolve(villagesMap.get(townId));
} else {
// 未命中
http
.get(`xxxx?regionId=${
townId}`)
.then((v) => {
const villages = v.data.payload;
villagesMap.set(townId, villages);
villagesMap.set('time', Date.now());
resolve(villages);
})
.catch((err) => {
reject(err);
});
}
});
};
Three. Summary
After joining the cache, the same request will not be repeated until the cache expires.
Front-end performance optimization involves many aspects, one of which is to reduce http/https requests, and the front-end caches interface data, which is extremely effective in scenarios where the frequency of data modification is low.