首页 > 解决方案 > 当用户尝试将随机字符串附加到 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;

我试图通过添加以下行将用户重定向到“未找到页面” - 但它仍然无法正常工作。

标签: javascriptreactjsreact-router-dom

解决方案


您需要像这样在组件中使用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;

推荐阅读