我正在尝试构建一个多页应用程序,而我在设置路线方面遇到了困难。从代码中可以看到,有一个导航栏,页脚和switch语句。 switch标签的最后一行是“找不到”页面,在该页面上,我不希望显示导航栏或页脚。我找不到实现它的方法。
<Router>
<NavbarPage />
<Switch>
<Route exact path="/" component={MyComponent} />
<Route path="/services/" component={ServiciiPage} />
<Route path="/contact/" component={Contact} />
<Route path="/portfolio" component={Portfolio} />
<Route component={My404Component} />
</Switch>
<Footer />
</Router>
答案 0 :(得分:0)
为要使用Routes
和Navbar
正常显示的组件创建一组Footer
。请执行以下操作:
class App extends React.Component{
render(){
const DefaultRoutes = () => {
return(
<div>
<NavbarPage/>
<Switch>
<Route exact path="/" component={MyComponent} />
<Route path="/services/" component={ServiciiPage} />
<Route path="/contact/" component={Contact} />
<Route path="/portfolio" component={Portfolio} />
</Switch>
<Footer/>
</div>
)
}
return(
<Router>
<Switch>
<Route component={DefaultRoutes}/>
</Switch>
</Router>
)
}
}
通过分隔这样的路由,Switch
组件将尝试在Route
中找到与URL匹配的DefaultRoutes
。如果是这样,它将使用Navbar和Footer渲染布局。
现在,让我们创建一个RedirectToNotFound
组件,如下所示:
import React from "react";
import { Redirect } from "react-router-dom";
const RedirectToNotFound = () => {
return <Redirect to="/notfound" />;
};
export default RedirectToNotFound;
现在,当用户转到未命名的路线时,它将导航到该组件,该组件将重定向到404组件。
import React from "react";
import ReactDOM from "react-dom";
import { Route, Switch, BrowserRouter } from "react-router-dom";
import My404Component from "./My404Component";
import NavbarPage from "./NavbarPage";
import Footer from "./Footer";
import MyComponent from "./MyComponent";
import RedirectToNotFound from "./RedirectToNotFound";
import "./styles.css";
class App extends React.Component {
render() {
const DefaultRoutes = () => {
return (
<div>
<NavbarPage />
<Switch>
<Route exact path="/" component={MyComponent} />
<Route path="/services/" component={ServiciiPage} />
<Route path="/contact/" component={Contact} />
<Route path="/portfolio" component={Portfolio} />
<Route component={RedirectToNotFound} />
</Switch>
<Footer />
</div>
);
};
return (
<BrowserRouter>
<Switch>
<Route component={My404Component} path="/notfound" />
<Route component={DefaultRoutes} />
</Switch>
</BrowserRouter>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);