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

如何使用twin.macro在React页面间传递数据?

React页面间传递state失败的解决方案

你当前使用的是原生<a>标签(通过as="a"指定),原生a标签并不支持state属性,所以你传递的state根本不会被携带到跳转后的页面。要在React项目中实现带state的页面跳转,必须使用React Router提供的Link组件。

具体修改步骤:

  1. 导入Link组件
    在页面A的文件顶部导入React Router的Link:
import { Link } from 'react-router-dom';
  1. 修改BuyNowButton的跳转配置
    将as="a"替换为as={Link},把href属性改成to,并通过to对象传递state:
<BuyNowButton 
  css={!plan.featured && highlightGradientsCss[index]}
  as={Link}
  to={{
    pathname: "/payment",
    state: { plan: plan } // 把plan数据存入state
  }}
>
  {primaryButtonText}
</BuyNowButton>
  1. 在页面B获取state
    页面B中使用useLocation的方式不变,现在可以正常拿到传递的数据:
import { useLocation } from 'react-router-dom';

// ...

const location = useLocation();
const plan = location.state?.plan; // 用可选链避免undefined报错
console.log(plan); // 查看传递的plan数据

额外注意:

  • 确保你的项目已正确配置React Router(比如用BrowserRouter包裹了整个路由结构)
  • location.state存储在内存中,若刷新页面B,state会变为undefined。如果需要刷新后仍保留数据,可考虑将数据存入URL参数、localStorage或sessionStorage。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:27:11