Reactjs 如何渲染仅显示SPA中特定组件的新管线?
我有一个登录页,它作为一个单页应用程序由多个路由组成。但现在我想添加另一个名为Reactjs 如何渲染仅显示SPA中特定组件的新管线?,reactjs,react-router,Reactjs,React Router,我有一个登录页,它作为一个单页应用程序由多个路由组成。但现在我想添加另一个名为/dashboard的路由,它显示来自API的实时数据,因此当用户单击仪表板的按钮时,他们看到的只是仪表板的内容,而不是仪表板上方的导航栏和页脚 function App() { return ( <Router> <Navbar /> <Switch> <Route
/dashboard
的路由,它显示来自API的实时数据,因此当用户单击仪表板的按钮时,他们看到的只是仪表板的内容,而不是仪表板上方的导航栏和页脚
function App() {
return (
<Router>
<Navbar />
<Switch>
<Route path="/" exact component={Home} />
<Route path="/process" exact component={Process} />
<Route path="/products" exact component={Products} />
<Route path="/team" exact component={Team} />
</Switch>
<Footer />
<Route exact path="/dashboard">
<Dashboard />
</Route>
</Router>
);
}
函数应用程序(){
返回(
);
}
下面的图片是我所说的,当点击仪表板
按钮时,导航栏和页脚仍然可见。现在,它只是在显示单词Dashboard。我希望这样,当用户单击仪表板
按钮时,仪表板才可见
您可以使用渲染功能将导航栏包装到路线中
在渲染函数中,可以访问匹配对象。Witch具有路径和url,因此您可以在呈现导航栏时自行筛选
可能是这样的代码:
<Route path="*" render={({match}) => {
if(match.url !== /*something*/){
return <Navbar />
}else{
// return null to skip rendering anything here
return null
}
}} />
{
如果(match.url!=/*某物*/){
返回
}否则{
//返回null以跳过此处的任何渲染
返回空
}
}} />
编辑:
可能更短,但您必须列出所有路线:
<Route path={['/', '/process', '/products', '/team']} exact component={Navbar} />
您还可以在路径内部使用正则表达式。需要使用匹配并指定当路径为/dashboard
时,导航栏和页脚不显示
工作,但也许有一个更优雅的解决方案
return (
<Router>
<Route
path="*"
render={({ match }) => {
if (match.url !== "/dashboard") {
return <Navbar />;
} else {
return null;
}
}}
/>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/process" exact component={Process} />
<Route path="/products" exact component={Products} />
<Route path="/team" exact component={Team} />
</Switch>
<Route
path="*"
render={({ match }) => {
if (match.url !== "/dashboard") {
return <Footer />;
} else {
return null;
}
}}
/>
<Route
path="*"
render={({ match }) => {
console.log(match);
if (match.url === "/dashboard") {
return <Dashboard />;
} else {
return null;
}
}}
/>
</Router>
);
返回(
{
如果(match.url!==“/dashboard”){
返回;
}否则{
返回null;
}
}}
/>
{
如果(match.url!==“/dashboard”){
返回;
}否则{
返回null;
}
}}
/>
{
控制台日志(匹配);
如果(match.url==“/dashboard”){
返回;
}否则{
返回null;
}
}}
/>
);
我用match.url==“/dashboard”
尝试了它,但不起作用。很抱歉,我前面没有运行代码。你能不能log(match)
不确定你必须使用哪一个。这是控制台的输出。log(match)
:path:“/”,url:“/”,params:{…},isExact:false}isExact:false参数:{uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuo:Object
你现在不在仪表板上了,对吗?你应该根据这个路径来测试它。即使我在仪表板上,它也会返回相同的结果。