【发布时间】:2020-05-11 06:13:28
【问题描述】:
我正在尝试在新页面上显示可点击对象的详细信息。我尝试了来自React Router Pass Param to Component 的一些示例,但成功有限。 唯一“有点”起作用的是 Alexander Luna 建议通过组件中的 ID 访问。但是,虽然这会返回 id 号,但我无法访问任何其他值,例如“title”。 我试过 globalStore,但是,错误消息告诉我它没有定义。我不确定这是否是我最好的选择。 最终我想要整个对象回来,因为我计划使用上下文,参见下面的“D”。
App) 我已经注释掉了我之前的尝试
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>
【问题讨论】:
-
你唯一的路由参数是
id(:id) 所以没有params.title。title在哪里被传递? -
你只需要id和title还是整个对象?
-
我正在尝试通过 API 访问标题,我已经在产品页面中完成了该操作。导出默认类 Product extends Component { render() { const { id, title, img, price, inCart } = this.props.product;返回(
-
Zohaib -- 我需要整个对象,id 和 title 只是为了测试,它们是“最远的”,其他尝试只是破坏了服务器。
-
您可以将对象传递给
Link参见reacttraining.com/react-router/web/api/Link/to-object
标签: javascript reactjs