【发布时间】:2023-01-13 19:39:44
【问题描述】:
我在浏览器的本地 JS 字典变量 asCache 中缓存了一些数据。然后我首先检查字典中是否存在该键。如果它存在,那么我只返回数据,否则我继续做 axios 请求。代码看起来像这样:
export default class ActivityStatsCard extends React.Component {
asCache = {} // cache dictionary
async getActiveTimePercentages(fromDate, toDate) {
var url = '/stats/ahs/';
let key = 'c-' + this.props.routeProps.match.params.cId
+ '-from-' + new Date(fromDate).toUTCString()
+ '-to-' + new Date(toDate).toUTCString()
// if the data is cached, return it (dont do axios request)
if (this.asCache.hasOwnProperty(key))
return this.asCache[key]
// if the data is not cached, make axios request
const axiosInstance = axios.create();
try {
const response = await axiosInstance.get(url,
{
params: {
'format': 'json',
'cId': this.props.routeProps.match.params.cId,
'FromDate': new Date(fromDate).toUTCString(),
'ToDate': new Date(toDate).toUTCString(),
'from_getPs': 'True'
}
}
)
let data = response.data
return data;
} catch (err) {
console.error(err);
}
}
//...
}
问题是,即使缓存了数据,它也显示它在开发工具的网络选项卡中发出了 xhr 请求。但是我觉得它并没有发出真正的请求,因为请求只需要 12 毫秒:
通常服务器端处理至少需要 55 毫秒,当我开始新会话并且没有数据缓存在 asCache 变量中时,我总是观察到这一点。但是如果它确实没有发出任何 xhr 请求,那么为什么它显示它已经在网络选项卡中完成了一些,如上面的屏幕截图所示?
【问题讨论】:
标签: javascript reactjs ajax axios xmlhttprequest