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

React中通过Route与Link传递Props至组件失败求助

问题排查与解决方案

1. 修正跳转路径的错误用法

你在Trips组件的Link中写了pathname: "/Spain/*",这是对React Router通配符的误用:

  • *是路由匹配规则的通配符,用于匹配该路径下的所有子路由,不能作为跳转路径的一部分。
  • 跳转时应使用实际路径,比如"/Spain",若有子路由可写"/Spain/xxx",无需加*。

修改后的Link代码:

<Link
   to={{
     pathname:
       selectedImage === "Spain"
         ? "/Spain"
         : selectedImage === "Italy"
         ? "/Italy"
         : selectedImage === "France"
         ? "/France"
         : null,
     state: {
       hotelParameters: hotelParameters,
       adultCount: adultCount,
       roomCount: roomCount,
     },
   }}
 >
   {/* 图片内容保持不变 */}
 </Link>

2. 确保App中的状态已正确更新

你通过Route直接向SpainPage传递props,但如果hotelParameters、adultCount、roomCount没有被前置组件正确更新,传递的就是初始值:

  • 检查前置表单组件是否调用了setHotelParameters、setAdultCount、setRoomCount来修改App中的状态。
  • 可以在App.jsx中添加日志验证状态值:
console.log("当前App状态:", hotelParameters, adultCount, roomCount);
return (
  {/* 路由渲染内容 */}
);

3. 给SpainPage的state接收添加容错处理

即使Link传递了state,用户直接刷新SpainPage时location.state会变为null,需添加默认值避免undefined:

import { useLocation } from "react-router-dom";
export default function SpainPage() {
  const location = useLocation();
  const { hotelParameters = {}, adultCount = 0, roomCount = 0 } = location.state || {};
  
  // 验证接收的值
  console.log("SpainPage接收的参数:", hotelParameters, adultCount, roomCount);
  return (
    {/* 页面内容 */}
  );
}

4. 确保Trips组件正确传递state到SpainPage

Trips组件通过useLocation拿到state后,要确保在Link的state中正确引用解构后的变量:

export default function Trips() {
  const location = useLocation();
  // 添加容错,避免location.state为null
  const { hotelParameters = {}, adultCount = 0, roomCount = 0 } = location.state || {};

  return (
    <Link
      to={{
        pathname: selectedImage === "Spain" ? "/Spain" : /* 其他路径 */,
        state: { hotelParameters, adultCount, roomCount },
      }}
    >
      {/* 图片内容 */}
    </Link>
  );
}

5. 检查嵌套路由的匹配逻辑

如果"/Spain/*"是用来匹配子路由的,需确保SpainPage组件内部使用Outlet渲染子路由,否则可能导致路由匹配异常,间接影响props传递。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:32:39