[英]Reactjs routing causing page render issues
I have the following App.js:我有以下 App.js:
function App() {
return (
<div className="App">
<Header></Header>
<HomePage></HomePage>
</div>
);
}
Anyone accessing the website should see the homepage first by default.默认情况下,访问该网站的任何人都应该首先看到主页。
I have a navigation menu with the following routing information:我有一个导航菜单,其中包含以下路由信息:
<Router>
<Switch>
<Route path='/login' component={Authentication} />
</Switch>
</Router>
When I click on the login menu link, the authentication page loads, but I can also see the homepage below when scroll down in the browser.当我单击登录菜单链接时,会加载身份验证页面,但在浏览器中向下滚动时,我也可以看到下面的主页。 How do I load only the page referenced in the router?
如何仅加载路由器中引用的页面?
SOLUTION:解决方案:
Added the following route to the router将以下路由添加到路由器
<Route exact path='/' component={Home} />
Different path in Route
shows different page (the component attribute in Route
), here is a demo and react-router docs maybe helps you. Route
中的不同路径显示不同的页面( Route
中的组件属性),这是一个演示,react-router 文档可能会对您有所帮助。 Good luck!祝你好运!
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; export default function App() { return ( <Router> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/users">Users</Link> </li> </ul> </nav> {/* A <Switch> looks through its children <Route>s and renders the first one that matches the current URL. */} <Switch> <Route path="/about"> <About /> </Route> <Route path="/users"> <Users /> </Route> <Route path="/"> <Home /> </Route> </Switch> </div> </Router> ); } function Home() { return <h2>Home</h2>; } function About() { return <h2>About</h2>; } function Users() { return <h2>Users</h2>; }
You have to add "exact path" keyword in the Route section like this: <Route exact path="/" component={Home} />
If you don't use "exact" it will render all the component which route contains "/".您必须在 Route 部分中添加“
<Route exact path="/" component={Home} />
path”关键字,如下所示: /”。
Use exact for this issue.对这个问题使用exact。
<Route exact path="/">
<Home />
</Route>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.