首页 > 解决方案 > 单击特定卡片时在另一个页面上呈现卡片详细信息

问题描述

卡片来自 JSON 文件。代码来自一个名为 painting.js 的文件。卡片都正确呈现,点击后它们会将我带到空白的paintingInfo.js 页面。我的问题是我应该在这个新的 paintingInfo.js 页面中包含什么,以便它呈现我存储在本地存储中的卡。React 相对较新,因此非常感谢任何帮助。基本上,我如何访问paintingInfo.js 页面中的本地存储以进行渲染?

  state = {
    cardInfo: [...cardInfo]
  };

  goToPaintingInfo = (cardInfo) => {
    localStorage.setItem("selectedPainting", cardInfo);
    this.props.history.push("/paintingInfo/:id");
  }

  render() {
    return (
      <React.Fragment>
        <Navbar className="navCustom d-flex justify-space-between" bg="light" variant="light">
          <Navbar.Brand href="/">SNR Arts</Navbar.Brand>
          <Nav className="ml-auto navCust">
            <Nav.Link href="/">Home</Nav.Link>
            <Nav.Link href="/paintings">Paintings</Nav.Link>
            <Nav.Link href="/contact">Contact</Nav.Link>
          </Nav>
        </Navbar>
        <div className="container-fluid">
          <div className="row align-items-center justify-content-between">
            {/* print out cards here */}

            {this.state.cardInfo.map(card => {
              return (
                <div className="col-12 col-sm-3 col-md-2 my-3" key={card.id}>
                  <img
                    src={card.image}
                    alt={card.name}
                    className="img-fluid img-thumbnail rounded indvCard bg-dark"
                    onClick = {()=>this.goToPaintingInfo(card.id)}
                  />
                </div>
              );
            })}
          </div>
        </div>

标签: javascriptreactjsreact-routerlocal-storagereact-router-dom

解决方案


点击卡片,而不是card.id你只需要发送card喜欢,

onClick = {()=>this.goToPaintingInfo(card)}
goToPaintingInfo = (cardInfo) => {
    localStorage.setItem("selectedPainting", JSON.stringify(cardInfo)); //store complete card
    this.props.history.push(`/paintingInfo/${cardInfo.id}`); //For this you must have Route to handle this request
}

在路线的某个地方,你必须有

<Route path="/paintingInfo/:id" exact component={paintingInfo} /> //Write appropriate component name

paintingInfo.js文件

state={
   card: JSON.parse(localStorage.getItem("selectedPainting"))
}

render(){
   return(
     <div>
        <img src={this.state.card.image}
             alt={this.state.card.name}
             className="img-fluid img-thumbnail rounded indvCard bg-dark"
        />
     </div>
   )
}

注意:this.props.history.push您只能使用Redirectfrom react-router-dompackage而不是。

import {Redirect} from 'react-router-dom'
goToPaintingInfo = (cardInfo) => {
    localStorage.setItem("selectedPainting", cardInfo); //store complete card
    return <Redirect to={`/paintingInfo/${cardInfo.id}`} />; //For this you must have Route to handle this request
} 

推荐阅读