我正在尝试制作导航栏,但是导航栏不会重定向到给定的页面。如果单击导航栏中的任何链接,它将更改URL栏中的路径,但不会重定向到该页面。我不确定是否遗漏了任何东西。当我用标签替换它时,它可以完美工作。
Navbar.js
import React from "react";
import { BrowserRouter as Router, Link, Switch } from "react-router-dom";
const Navbar = () => {
return (
<Router>
<Switch>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/articles">Articles</Link>
</li>
<li>
<Link to="/articles-all">All articles</Link>
</li>
</ul>
</nav>
</Switch>
</Router>
);
};
export default Navbar;
App.js
import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import './App.css'
//pages
import Home from "./Pages/Home";
import About from "./Pages/About";
import Articles from "./Pages/Articles";
import ArticlesList from "./Pages/ArticlesList";
//components
import Navbar from './components/Navbar';
const App = () => {
return (
<div>
<Navbar/>
<Navigation />
</div>
);
};
export default App;
const Navigation = () => {
return (
<Router>
<div id="page-body">
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/articles" component={Articles} />
<Route path="/articles-all" component={ArticlesList} />
</div>
</Router>
);
};
答案 0 :(得分:2)
由于您在导航中定义了路由器,并且在Navbar
中定义了另一个路由器,因此链接无法与导航中的路由器组件进行通信,因为它们仅与最近的父路由器组件进行通信
您必须使用单个Router实例才能在您的App中执行无缝导航。此外,链接不需要开关组件,Route
const App = () => {
return (
<Router>
<Router component={Navbar}/> // rendered as default route so that they receive router props
<Router component={Navigation} />
</Router>
);
};
export default App;
const Navigation = () => {
return (
<div id="page-body">
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/articles" component={Articles} />
<Route path="/articles-all" component={ArticlesList} />
</div>
);
};
const Navbar = () => {
return (
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/articles">Articles</Link>
</li>
<li>
<Link to="/articles-all">All articles</Link>
</li>
</ul>
</nav>
);
};
export default Navbar;
答案 1 :(得分:1)
这是一个有效的代码和邮箱URL https://codesandbox.io/s/frosty-black-3i8hp?file=/src/App.js
您正在包装带有browserRouter和Switch的链接。这些API仅用于包装路由。
因此,它无法与您的react应用进行良好的沟通。