javascript - 每次点击触发不同的 API 调用
问题描述
我有列表,每个点击的项目都会触发不同的 API 请求。每个请求都有不同的持续时间。成功后,我正在显示一些数据。
问题是,当我单击需要大约 6000 年才能加载的项目#1 以及在需要 2000 年才能加载的项目#2 之后,我将显示最后点击的项目 - 这是项目#2,因为它已经加载并且一旦 item#1 收到数据,我的数据将更改为该数据。这是错误的,因为我想显示最新点击的数据。
这就是我处理事件的方式:
newList.on('click', 'li', (e) => {
let id = $(e.currentTarget).data("id");
store.getCharacterDetails(id).then(docs => {
this.clearDetails();
this.charDetails = docs;
this.displayDetails(this.charDetails);
})
我的 API 是来自 store 对象的模拟。
我想这可以按预期工作,但我确实希望最后一个触发的请求有效。
解决方案
创建charDetails
一个对象来保存所有结果,并以 id 为键。跟踪最后点击的 id。
// in constructor
this.charDetails = {};
this.lastId = null;
newList.on('click', 'li', (e) => {
let id = $(e.currentTarget).data("id");
this.lastId = id;
if (this.charDetails[id] === id) { // don't cancel requests, cache them!
this.displayDetails(this.charDetails[id])
} else {
store.getCharacterDetails(id).then(docs => {
// this runs later, cache the result
this.charDetails[id] = docs;
if (id === lastId) { // only update UI if the id was last clicked
this.displayDetails(docs)
}
});
}
});
推荐阅读
- php - composer 需要没有 dev-master 的本地 git 包
- bash - bash 脚本中的 sqlite3 在 INSERT 上中断
- canvas - 你如何让 canvas% 对象响应鼠标悬停?
- microsoft-graph-api - 添加日历事件,然后检索并更新该事件
- html - 跳转到表格行并在 html 中突出显示它?
- javascript - 获取 React Native 中有多少视图是可见的?
- python - Pytest:如何使用从夹具返回的列表对测试进行参数化?
- sql - offsetDateTime 非法ArgumentException nhibernate
- javascript - 在循环内为 HTML 制作换行符 For PHP
- python - 实现接收数组并将每个元素乘以给定 int 的函数