javascript - 反应路由器访问对象详细信息
问题描述
我正在尝试在新页面上显示可点击对象的详细信息。我尝试了一些来自React Router Pass Param to Component的示例,但成功有限。唯一“有点”起作用的是 Alexander Luna 建议通过组件中的 ID 访问。但是,虽然这会返回 id 号,但我无法访问任何其他值,例如“title”。我试过 globalStore,但是,错误消息告诉我它没有定义。我不确定这是否是我最好的选择。最终我想要整个对象回来,因为我计划使用上下文,参见下面的“D”。
应用程序)我已经注释掉了我之前的尝试
class App extends Component {
render() {
return (
<React.Fragment>
<Navbar />
<Switch>
<Route exact path="/" component={ProductList} />
<Route path="/cart" component={Cart} />
<Route exact path="/details/:id" component={Details} />
{/* <Route exact path="/details/:id" render={(props) => <Details globalStore={globalStore}
{...props} /> } /> */}
{/* <Route exact path="/details/:id" render={(props)=>{ <Details id={props.match.params.id}/>}}
/> */}
<Route component={Default} />
我要渲染的详细信息页面。
import React, { Component } from "react";
export default class Details extends Component {
render() {
return(
<div>
<h2>{this.props.match.params.id}</h2>
<h2>{this.props.match.params.title}</h2>
</div>
产品页面,我正在使用此链接点击查看详细信息。
xport default class Product extends Component {
render() {
const { id, title, img, price, inCart } = this.props.product;
return (
<ProductWrapper className="col-9 mx-auto col-md-6 col-lg-3 my-3">
<div className="card">
<div className="img-container" onClick={() => console.log('you clicked container')}
>
<Link to={`/details/${ this.props.product.id }`} >
<img src={img} alt="product" className="card-img-top" />
</Link>
D - 这是原始代码的样子,我想使用 {title} 标签,但我不知道是否需要“value =>”等。
<ProductConsumer>
{value => {
const {
id,
company,
img,
info,
price,
title,
size,
} = value.Product;
return (
<div className="container py-5">
{/* title */}
<div className="row">
<div className="col-10 mx-auto text-center text-slanted text-blue my-5">
<h1>{title}</h1>
</div>
</div>
解决方案
你需要一个额外的参数
<Route exact path="/details/:id/:title" component={Details} />
export default class Details extends Component {
render() {
return(
<div>
<h2>{this.props.match.params.id}</h2>
<h2>{this.props.match.params.title}</h2>
</div>
);
}
}
// In Product component
<Link to={`/details/${ this.props.product.id }/${this.props.product.title}`} >
<img src={img} alt="product" className="card-img-top" />
</Link>