卡片来自JSON文件。代码来自一个名为paintings.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>
答案 0 :(得分:1)
点击卡片时,您只需发送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
软件包中的react-router-dom
。
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
}