You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组遍历路由跳转疑问:触发路由后如何继续完成数组遍历?

问题:路由跳转后如何继续完成数组遍历?

给定如下对象数组:

const studentDetails = [
    {id:1, name:"Mike", stream:"Science", status:"active"},
    {id:2, name:"Kelly", stream:"Commerce", status:"inactive"},
    {id:3, name:"Bob", stream:"Law", status:"inactive"},
]

需求是遍历该数组,当元素的status为'inactive'时,通过router.push跳转到/pageB页面。当前实现代码:

studentDetails.map(studentDetail => {
    if(studentDetail.status === 'inactive'){
        router.push("/pageB")
    }
})

疑问:当处理id为2的元素触发路由跳转后,如何继续完成对id为3的元素的遍历?


核心说明

一旦执行router.push,当前页面的JS上下文会被浏览器销毁(路由跳转后会加载新页面的代码),原页面的遍历逻辑会直接中断,所以没法在跳转后继续执行原页面的遍历。要实现“遍历所有符合条件的元素”+“跳转”的需求,得换思路:

方案1:先全量收集,再跳转并传递数据

如果需要确认所有inactive的学生后再跳转,同时要把这些数据带到目标页面,可以先遍历过滤出所有符合条件的元素,再执行跳转:

// 先遍历收集所有状态为inactive的学生
const inactiveStudents = studentDetails.filter(student => student.status === 'inactive');

// 存在符合条件的学生时触发跳转
if (inactiveStudents.length > 0) {
    // 将数据存入本地存储或路由参数,方便pageB获取
    localStorage.setItem('inactiveStudents', JSON.stringify(inactiveStudents));
    router.push("/pageB");
}

这样既完成了全量遍历,又能把需要的数据传递到目标页面处理。

方案2:先完成所有处理逻辑,再统一跳转

如果需要对每个inactive学生执行特定处理后再跳转,要把所有处理逻辑放在跳转前完成:

// 先遍历完成所有需要的处理
studentDetails.forEach(student => {
    if (student.status === 'inactive') {
        // 这里执行对该学生的处理逻辑,比如记录、校验等
        console.log(`已处理学生:${student.name}`);
    }
});

// 检查是否存在符合条件的学生,再执行跳转
const hasInactiveStudent = studentDetails.some(student => student.status === 'inactive');
if (hasInactiveStudent) {
    router.push("/pageB");
}

内容的提问来源于stack exchange,提问作者Mohit Chauhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:15:41