在React中,我们可以使用react-router-dom来进行路由跳转,并且可以通过URL参数或者state参数来传递数据。
1. URL参数传递:
- 在Link组件中设置to属性为一个包含参数的URL路径,例如:`<Link to="/detail/123">详情页</Link>`。
- 在Route组件中设置路径为`/detail/:id`,其中`:id`表示参数,可以通过this.props.match.params.id来获取参数的值。
2. state参数传递:
- 在Link组件中使用对象形式的to属性,例如:`<Link to={{ pathname: '/detail', state: { id: 123 } }}>详情页</Link>`。
- 在目标组件中通过this.props.location.state来获取参数的值。
示例代码如下:
// 跳转到详情页并传递参数
<Link to={{ pathname: '/detail', state: { id: 123 } }}>详情页</Link>
// 路由配置
<Route path="/detail/:id" component={Detail} />
// 目标组件中获取参数
class Detail extends React.Component {
render() {
const { id } = this.props.match.params;
const { id } = this.props.location.state;
return (
<div>
<h1>详情页</h1>
<p>ID: {id}</p>
</div>
);
}
}
需要注意的是,state参数传递方式不建议用于需要持久化的数据,因为页面刷新后数据会丢失。建议使用URL参数或其他状态管理库来管理这种情况。