javascript - 当用户尝试将随机字符串附加到 URL 时,如何将用户重定向到“未找到页面”?
问题描述
我目前正在使用 react.js 开发一个网络应用程序。当用户尝试将随机字符串附加到 URL 时,我想将用户重定向到静态“未找到页面”。
当前代码如下:
const Routes = () => {
return (
<Switch>
<Route path = '/home' component={Home1}/>
<Route path = '/' component={Home}/>
<Route path="*" component={NotFoundPage}/>
</Switch>
);
};
export default Routes;
我试图通过添加以下行将用户重定向到“未找到页面” - 但它仍然无法正常工作。
解决方案
您需要像这样在组件中使用exact
道具:Route
const Routes = () => {
return (
<Switch>
{
//exact keyword used so only the exact path will result showing the component
}
<Route exact path='/' component={Home}/>
<Route exact path='/home' component={Home1}/>
{
// Not using exact keyword will result in showing NotFoundPage to every other URL except above two paths
}
<Route component={NotFoundPage}/>
</Switch>
);
};
export default Routes;
推荐阅读
- node.js - 由于在 EJS 中使用 If-else 语句,我的 Bootstrap 表单完全消失了
- spring-boot - 为什么我需要在构建之前手动运行 clean?
- java - 当应用程序进入后台时如何停止媒体播放器?
- operating-system - gem5 se模式如何执行具有操作系统依赖的程序?
- mysql - 如何将字符串拆分为单列并在SQL中的同一列中排列相同
- django - Mongoengine插入方法不在数据库中插入值
- python - 在 Dash 框架中动态添加 HTML 输入
- ajax - 带有按钮 id 的 Ajax Post URL,Django 服务器
- node.js - 传递模块对象的所有导出
- linux - 因误用linux命令mv而查找文件