【发布时间】:2021-10-27 03:01:46
【问题描述】:
我有一个卡片轮播。每张卡片都有一些数据,如果我点击卡片上的按钮。我想在不同页面上的不同组件中呈现该特定卡片的详细信息,即 item-details。
如何在类组件中实现这一点?地图中有一个 ID,我可以在我尝试呈现卡片的完整详细信息的详细信息页面中使用该 ID 发送。
{this.state.data.map((item, idx) => {
return (
<div key={`edth_${idx}`} className="col-12 col-sm-6 col-lg-4 item explore-item" data-groups={item.group}>
<div className="card">
<div className="image-over">
<img className="card-img-top" src={item.img} alt="" />
</div>
<div className="card-caption col-12 p-0">
<div className="card-body">
<a href="/item-details">
<h5 className="mb-0">{item.title}</h5>
</a>
<div className="card-bottom d-flex justify-content-between">
<span>{item.price}</span>
<span>{item.count}</span>
</div>
<Link to={{pathname: '/item-details',state: [{img:'item.img',count: 'item.count', title: 'item.title', price: 'item.price'}]}} className="btn btn-bordered-white btn-smaller mt-3"> <i className="icon-handbag mr-2" />Check it out</Link>
</div>
</div>
</div>
</div>
);
})}
</div>
我已经添加了来自 react 路由器的链接,但我仍然不知道如何在 /item-details 中的组件中使用它。
发现我可以在类组件中使用路由器而不是 useLocation,所以...
在 item-details 页面中导入 useRouter 并在 render() 中像这样使用:
render() {
const { location } = this.props;
return (
<div className="item-info">
{location && location.img && <div className="item-thumb text-center">
<img src={location.img} />
</div>}
);
通过这样做,我没有收到任何错误。但是img没有显示。
【问题讨论】:
-
到底是什么问题?
-
@EmmanuelPonnudurai 当我点击 我想传递项目的按钮时详细信息,如 item.count item.title 到 /item-details 页面。我将在哪里使用我点击的特定卡片的详细信息。我如何做到这一点?
-
好的。我看到的最简单的方法是,将它们作为 queryParams 传递。类似
href="/item-details?count={count}&title={titlle}"。这也意味着您重定向到的其他页面应该能够使用这些 queryParams 并使用它们。如果您想对此类操作提供丰富的支持,则可以使用 react 路由器库,但这与您的应用程序无关,因为我不知道您的应用程序的完整构成。 -
有什么问题?路由状态不工作吗?访问location object中接收路由组件的路由状态。
-
您是否尝试过其他多种访问
location对象的方法?你能分享一下你是如何尝试访问路由状态的吗?我们能看到它是如何被路由器渲染的吗? stackoverflow.com/help/minimal-reproducible-example
标签: reactjs react-router state