首页 > 解决方案 > Reactjs:如何从每个现有 URL 中删除 page-not-found 组件?

问题描述

我正在构建反应应用程序。
如果用户键入了错误的 URL,NoMatch则会显示该组件(这很好)。

挑战在于,当用户键入现有 URL 时,会显示两个组件。NoMatch组件和预期组件都会出现。

注意:我在stackoverflow上发现了一些关于此的问题,但没有一个解决方案对我有用。我正在使用一个<PrivateRoute>react-router-dom

应用程序.js

<Provider store={store}>
    <Router>
        <Switch>
            <Route exact path="/login" component={Login}/>
            <Fragment>
                <Navigationbar/>
                <div className="main-part">
                    <Sidebar/>
                    <main className="content shrunk-sidebar">
                        <PrivateRoute path="/" exact component={Home}/>
                        <PrivateRoute path="/files" exact component={Files}/>
                        <PrivateRoute path="/new_app" exact component={NewApp}/>
                        <PrivateRoute path="/applications/:app_name" exact component={Application} />
                        <PrivateRoute path="*" component={NoMatch}/>
                    </main>
                </div>
            </Fragment>
        </Switch>
    </Router>
</Provider>

PrivateRoute.js

const PrivateRoute = ({component: Component, auth, ...rest}) => (
    <Route
        {...rest}
        render={props =>
            auth.isAuthenticated ? (
                <Component {...props} />
            ) : (
                <Redirect
                    to={{
                        pathname: "/login",
                        state: {from: props.location}
                    }}
                />
            )
        }
    />
);

这就是我遇到的问题。 在此处输入图像描述

知道我做错了什么,我没有得到我想要的结果吗?

标签: reactjsreact-router-dom

解决方案


Switch仅适用于它的直接子代,当您在其中添加类似 a 的Fragment内容时,Switch 将失去其对其Route内部组件的影响。

在您的情况下,您可以简单地移动Switch内部以包含PrivateRoute组件数组以使其工作

<Provider store={store}>
    <Router>
        <Switch>
            <Route exact path="/login" component={Login}/>
            <Fragment>
                <Navigationbar/>
                <div className="main-part">
                    <Sidebar/>
                    <main className="content shrunk-sidebar">
                        <Switch>
                            <PrivateRoute path="/" exact component={Home}/>
                            <PrivateRoute path="/files" exact component={Files}/>
                            <PrivateRoute path="/new_app" exact component={NewApp}/>
                            <PrivateRoute path="/applications/:app_name" exact component={Application}/>
                            <PrivateRoute path="*" component={NoMatch}/>
                        </Switch>
                    </main>
                </div>
            </Fragment>
        </Switch>
    </Router>
</Provider>

推荐阅读