如何从特定history.location.pathname获取对应FlashCard数组对象
核心需求与现有问题
调用getAllFlashCardsFromQuest()接口时,会返回全量历史创建的所有页面下的FlashCard闪卡数据,目前的实现无法筛选出仅归属指定pathname的闪卡,需要找到可精准过滤闪卡数组、匹配目标路径的实现方案。
当前存在问题的实现代码:
async function getCards() { let cardsValues = await getAllFlashCardsFromQuest() as FlashCard[] let cardsFiltered = cardsValues.filter(()=>{ return history.location.pathname === 'CriarAlternativaQuest' }) console.log(cardsFiltered) setCards(cardsFiltered) }
现有实现的问题点
filter方法的回调没有接收遍历过程中的单个闪卡实体参数,完全没有基于闪卡自身的属性做判断- 过滤逻辑只是全局
history.location.pathname和固定字符串的比对,对数组中每一条闪卡都会返回同一个布尔结果:要么保留全部拉取到的闪卡,要么返回空数组,根本无法实现按闪卡归属路径筛选的效果 - 从闪卡对象的结构定义可见,每个闪卡实体内部都存储了自身关联的来源页面路径属性,具备前端精准过滤的基础条件
可落地的实现方案
方案1:基于闪卡自身的路径属性做前端过滤(适配当前接口不支持传参的场景)
调整filter回调的逻辑,逐行比对单个闪卡的来源路径字段和目标路径,参考修正后的代码:
async function getCards() { const allCards = await getAllFlashCardsFromQuest() as FlashCard[] const targetPath = 'CriarAlternativaQuest' const matchedCards = allCards.filter(card => { // 替换为闪卡结构中实际存储来源路径的字段名即可 return card.sourcePagePath === targetPath }) console.log(matchedCards) setCards(matchedCards) }
方案2:适配接口传参直接拉取目标数据(更优的性能实现)
确认getAllFlashCardsFromQuest()是否支持接收路径查询参数,如果支持则直接将目标路径作为参数传入,让数据层直接返回对应路径下的闪卡,避免拉取全量数据到前端做冗余过滤,参考实现:
async function getCards() { const targetPath = 'CriarAlternativaQuest' // 直接传入目标路径参数,获取匹配的闪卡列表 const matchedCards = await getAllFlashCardsFromQuest(targetPath) as FlashCard[] setCards(matchedCards) }
开发注意:如果闪卡对象中存储的路径是带前缀的完整路径片段,过滤时需要提前做路径片段截取匹配,避免因为格式差异导致过滤失效。
内容的提问来源于stack exchange,提问作者Lucas Rocha
相关产品推荐
相关产品推荐

