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

点击浏览器回退按钮时如何保留React state及路由传参?

问题根源

  1. React Router 规定路由跳转携带的状态需要放在 to 对象的官方字段 state 中,你自定义的 Props 字段不会被持久化到 history 栈,页面回退、刷新时都会丢失。
  2. 你在 Page1 中读取的字段名 aboutProps 和你传递的 Props 字段不匹配,本身就无法拿到正确值,且没有做非空判断,读取 undefined 的属性时直接触发报错。

修复步骤

1. 修改 Home 页 Link 传参逻辑

将需要传递的参数放到官方规定的 state 字段中:

<Link
  style={{ textDecoration: "none", color: "inherit" }}
  to={{
    pathname: "/page1",
    state: { categoryID: val.id, categoryName: val.name }
  }}
/>;

2. 修改 Page1 取值逻辑,增加兼容判断

通过 props.location.state 读取 history 中存储的路由状态,添加可选链和兜底值避免空值报错,同时把接口调用放到 componentDidMount 生命周期中做合法性校验:

class BuyerItems extends Component{
    constructor(props) {
        super(props);
        this.state = {
          // 可选链读取+兜底值,避免state不存在时的报错
          id: props.location.state?.categoryID ?? '',
          name: props.location.state?.categoryName ?? '',
          gigs: [],
        }
      }

      componentDidMount() {
        // 参数合法时再调用接口
        if (this.state.id) {
          this.getGigs();
        } else {
          // 可选兜底逻辑:参数丢失时跳回首页,避免页面异常
          this.props.history.replace('/');
        }
      }
      // 其余业务逻辑保持不变
}

可选优化(参数持久化)

如果需要支持用户直接刷新 Page1 也能保留参数,可以把参数拼到路由路径上,示例路由配置如下:

// 路由配置
<Route path="/page1/:categoryID/:categoryName" component={BuyerItems} />

// Link跳转写法
<Link to={`/page1/${val.id}/${val.name}`} />

// Page1 取值方式
this.state.id = props.match.params.categoryID

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 15:18:01