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

React中使用Link组件实现按保单类型动态跳转详情页

保单详情跳转路径取值错误修复方案

问题背景

首页陈列各类保单展示卡片,每张卡片顶部设置「详情」按钮,点击后跳转至对应保单的详情页。单张保单仅归属一种类型,不同类型对应固定跳转路径:

车辆保单跳转路径:/policies/vehicle/detail
住房保单跳转路径:/policies/housing/detail

首页支持同时加载展示多个保单产品,现有跳转代码存在逻辑错误:activePolicies为数组类型,无法直接通过activePolicies.policyGroup的写法读取属性拼接路径,原有错误代码片段如下:

<Link to={{ pathname: history.location.pathname + activePolicies.policyGroup + '/details', state: { policy: activePolicy } }}>
  {t('general.details')}
  <AS.KeyboardArrowRightIcon />
</Link>

修复方案

核心错误点是混淆了数组和单个数组项的取值逻辑:保单卡片是遍历activePolicies数组逐张渲染的,policyGroup是单个保单对象的属性,不存在于数组本身。

  • 遍历activePolicies数组渲染卡片时,拿到当前循环项的单个保单对象,从该对象上读取policyGroup字段拼接路径即可,修正后的代码参考:
{
  // 遍历保单数组逐张渲染卡片
  activePolicies.map((currentPolicy) => {
    // 约定currentPolicy.policyGroup返回值:车辆保单为'vehicle',住房保单为'housing',直接拼接绝对路径
    const detailPath = `/policies/${currentPolicy.policyGroup}/detail`
    return (
      <div className="policy-card" key={currentPolicy.policyId}>
        {/* 卡片其余展示内容略 */}
        <Link
          to={{
            pathname: detailPath,
            state: { policy: currentPolicy }
          }}
        >
          {t('general.details')}
          <AS.KeyboardArrowRightIcon />
        </Link>
      </div>
    )
  })
}
  • 兼容处理:如果接口返回的保单类型标识和路径要求的字段不匹配,可以加一层映射转换,避免硬编码出错:
// 类型标识映射表,key为接口返回的类型值,value为路径要求的字段
const TYPE_PATH_MAP = {
  car: 'vehicle',
  house: 'housing'
}
// 拼接路径时先做值转换
const detailPath = `/policies/${TYPE_PATH_MAP[currentPolicy.policyType]}/detail`
  • 不要用当前路由路径history.location.pathname做相对拼接,直接写固定前缀的绝对路径,避免嵌套路由场景下出现路径重复拼接的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 15:33:14