如何呈现仅显示SPA中特定组件的新路线?

时间:2020-10-13 03:18:50

标签: reactjs react-router

我有一个登陆页面,该页面由多条路线组成,作为一个页面应用程序。但是,现在我想添加另一条名为/dashboard的路由,该路由显示来自API的实时数据,因此当用户单击dashboard的按钮时,他们看到的只是仪表板的内容,而不是导航栏的内容。以及仪表板上方的页脚。

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按钮时,导航栏和页脚仍可见。它现在仅显示单词Dashboard。我想要它,以便当用户单击Dashboard按钮时仅显示面板。

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用渲染功能将导航栏包裹在一条路线中。 Route render

在render函数中,您可以访问match对象。 Witch具有路径和URL,因此您可以在呈现导航栏时过滤自己。 match

也许是这样的代码:

<Route path="*" render={({match}) => {
    if(match.url !== /*something*/){
        return <Navbar />
    }else{
        // return null to skip rendering anything here
        return null
    }
}} />

编辑: 也许更短,但是您必须列出所有路线:

<Route path={['/', '/process', '/products', '/team']} exact component={Navbar} />

您也可以在路径内使用正则表达式。

答案 1 :(得分:0)

需要使用匹配项,并指定当路径为/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>
    );
相关问题