javascript - 单击特定卡片时在另一个页面上呈现卡片详细信息
问题描述
卡片来自 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>
解决方案
点击卡片,而不是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
您只能使用Redirect
from react-router-dom
package而不是。
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
}
推荐阅读
- mysql - mysql group 组的行
- blob - Outlook 2016 桌面客户端-保存文件不起作用
- javascript - 我在@Component 中遇到主机问题
- entity-framework - 在 EF 核心中禁用跟踪返回跟踪错误
- c# - 无法解析符号“notnull”
- apache-spark - 调用 split() 函数时出现“split”的 Pyspark 错误不在列表中
- netcdf - 连接具有不同变量的 netcdf 文件 - 使用 nco
- vue.js - 嵌套样式在我的组件样式中不起作用
- java - JSON Schema 中使用 Jackson 注释的自定义属性关键字
- ios - iOS 13:带有 LeftView 间距问题的 UITextField - Xcode 11