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

原生JavaScript实现SPA路由时动态商品详情页跳转异常问题求助

问题排查与修复方案

  • 路由匹配逻辑错误:你当前的商品路由判断是严格等于#product/id,但实际商品链接的hash是#product/[具体id值](比如#product/1、#product/2),完全不匹配,所以永远进不了这个判断分支。
  • 参数传递缺失:就算进入分支,你调用ui.showSingleProduct()没有传入对应商品数据,方法渲染的时候找不到product对象,自然会报错。
  • 全局currentPath未更新:这个变量是在window.onload执行时仅读取一次window.location.pathname,hash变化不会改变pathname,而且你也没有在hashchange事件里更新这个变量,所以它永远是初始值/。

具体修改代码

修改hashchange事件的匹配逻辑即可:

window.addEventListener("hashchange", () => {
    const CurrentPath = window.location.hash;
    console.log(CurrentPath)
    if (CurrentPath === '#about') {
        container.innerHTML = about;
        console.log(currentPath)
        console.log(CurrentPath)
    } else if (CurrentPath === '#contact') {
        container.innerHTML = contact;
        console.log(currentPath)
        console.log(CurrentPath)
        // 新增正则匹配动态商品路由
    } else if (/^#product\/\d+$/.test(CurrentPath)) {
        // 提取路由里的商品id
        const productId = CurrentPath.split('/')[1];
        // 请求对应商品数据后再渲染
        http.get(`${productsURL}/${productId}`).then(product => {
            ui.showSingleProduct(product);
        })
        console.log(CurrentPath);
        console.log(container.innerHTML)
    }
});

可选优化建议

你当前定义的myRouter路由表没有实际投入使用,后续可以把路由匹配逻辑抽离到和路由表关联,避免写过多if else判断,维护性更高。如果需要用到全局的路径变量,可以在hashchange事件里同步更新currentPath的值即可。

内容的提问来源于stack exchange,提问作者Szabi Vojtek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:27:05