Issues
- 我不知道为什么,但你似乎不使用
Link
组件在您的应用程序中保持一致;当使用锚点时(<a>
)标记这些类型的链接将重新加载页面和您的应用程序。手动设置时也会出现类似的问题window.location.href
.
- The
Image
没有正确访问通过的路由状态。
Solution
App
将您的路线从更具体到最不具体重新排序,并从Switch
组件,仅Route
and Redirect
组件是有效的子组件。
function App(props) {
return (
<>
<Router>
<Switch>
<Route path="/gallery" component={GalleryList} />
<Route path="/image" component={Image} />
<Route path="/" component={Home} />
</Switch>
</Router>
</>
);
}
Home
Use Link
组件进入图库。
import { Link } from "react-router-dom";
...
<Link to="/gallery">
<h4>Click Here to Enter Gallery!</h4>
</Link>
图库列表
Use Link
返回主页的链接组件。
import { Link } from "react-router-dom";
...
<Link to="/">Home</Link>
画廊容器
一致地引用图像源,即src
。也传递图像id
在路线状态下,使用Link
.
const GalleryConatiner = (props) => {
return (
// generates the gallery list!
<ul>
<li className={styles["gallery-list"]}>
<Link
to={{ pathname: "/image", state: { id: props.id, src: props.src } }}
>
<div
className={styles["div-gallery"]}
style={{
backgroundImage: `url(${props.src})`,
height: 250,
backgroundSize: "cover"
}}
></div>
</Link>
</li>
</ul>
);
};
src/公共/图像
Use a Link
返回画廊的链接。使用useLocation
钩子来访问传递的路由状态。
import { Link, useLocation } from 'react-router-dom';
const Image = (props) => {
const { state: { id, src } = {} } = useLocation();
return (
<section>
<h1 className={styles["h1-wrapper"]}>Image :{id}</h1>
<div className={styles.wrapper}>
<Link to="/gallery">BACK TO GALLERY</Link>
<ImageContainer id={id} key={id} src={src} />
</div>
</section>
);
};
src/Public/ImageContainer
目前尚不清楚您对此组件的计划是什么,请单击div
将传递的图像渲染为背景,因此只需删除window.location.href
逻辑与history.push
如果您想导航到其他地方。您可以访问history
对象通过useHistory
反应钩子。
Demo