[英]React Router loads URL in address bar but doesn't load component
Codesandbox link here . Codesandbox 链接在这里。
When a user clicks on a link, it should load the component in '/details'.当用户单击链接时,它应该在“/details”中加载组件。 However on click, it does load /details in the address bar but the component doesn't actually load.
但是,单击时,它会在地址栏中加载 /details,但实际上并未加载该组件。 It only loads on going separately to /details manually in the address bar.
它只会在地址栏中手动单独加载到 /details。
Routes.js路由.js
const Routes = () => {
return (
<BrowserRouter>
<Switch>
<Route exact path="/" component={App} />
<Route exact path="/details" component={MachineDetail} />
</Switch>
</BrowserRouter>
);
};
MachineCard.js机器卡.js
export default function MachineCard({ image, title, weight, power }) {
return (
<>
<div className="col-lg-4">
<div className="card">
<Router>
<Link to="/details">
<img className="img-fluid" src={image} alt={title} />
<h2>{title}</h2>
</Link>
</Router>
<p>Operating weight: {weight}</p>
<p>Power: {power}</p>
</div>
</div>
</>
);
}
Any idea why it won't load the '/details' component in the browser?知道为什么它不会在浏览器中加载“/details”组件吗?
This issue is that you have multiple routers in your app, but you only need one.这个问题是您的应用程序中有多个路由器,但您只需要一个。 Since you already have the router defined in your index file, you can go ahead and remove it from
MachineCard.js
.由于您已经在索引文件中定义了路由器,您可以继续将其从
MachineCard.js
删除。
Your MachineCard.js
component can therefore be simplified to this:因此,您的
MachineCard.js
组件可以简化为:
export default function MachineCard({ image, title, weight, power }) {
return (
<>
<div className="col-lg-4">
<div className="card">
<Link to="/details">
<img className="img-fluid" src={image} alt={title} />
<h2>{title}</h2>
</Link>
<p>Operating weight: {weight}</p>
<p>Power: {power}</p>
</div>
</div>
</>
);
}
I think your problem is incorrect naming.我认为您的问题是命名不正确。 In your route files you are using MachineDetail but you are exporting MachineCard.
在您的路线文件中,您使用的是 MachineDetail,但您正在导出 MachineCard。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.