reactjs - 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}
}}
/>
)
}
/>
);
知道我做错了什么,我没有得到我想要的结果吗?
解决方案
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>
推荐阅读
- typescript - 打字稿:是未定义联合的简写,字符串是可选属性类型吗?
- android - 如何为颤振绘图应用程序实现橡皮擦功能
- apache-spark - 如何动态更改架构?
- vb.net - vb.net usercontrol 如何更新我的属性
- javascript - 从时间服务器更新版权年份
- java - 并非所有请求的模块都可以启用 - org-netbeans-modules-nbjavac.jar
- python - 是否可以使键盘模块与 pygame 和线程一起使用
- kubernetes - dev k8s master 显示额外负载并导致无法获取获取 pod 的输出
- string - 我想在熊猫中添加两个具有字符串形式的时间值的列表
- php - Symfony http:来自 [::1] 的 TLS 握手错误