点击浏览器回退按钮时如何保留React state及路由传参?
问题根源
- React Router 规定路由跳转携带的状态需要放在
to对象的官方字段state中,你自定义的Props字段不会被持久化到 history 栈,页面回退、刷新时都会丢失。 - 你在 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
相关产品推荐
相关产品推荐

