反应路由器 v4 默认页面(未找到页面)

新手上路,请多包涵

这是共同的目的,将不匹配的请求定向到未找到的页面。

用 react-router v4 做这个看起来像以前的版本,我希望这个示例可以在下面工作。链接工作正常,但我希望 NotFound 组件只请求未知 url;但它总是在那里。

 import {
  BrowserRouter as Router,
  Route,
  Link
} from 'react-router-dom'

class Layout extends Component {
  render() {
    return (
    <Router>
      <div className="App">
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/user">User</Link></li>
        </ul>
        <Route exact path="/" component={Home}/>
        <Route path="/user" component={User}/>
        <Route path="*" component={Notfound}/>
      </div>
  </Router>
    );
  }
}

在此处输入图像描述在此处输入图像描述

它从 path="*" 代表所有请求和未找到的组件总是在那里,但我怎么能说隐藏这个组件以获得有效的 url 路径?

原文由 TyForHelpDude 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 878
2 个回答

React Router 的 No Match 文档 涵盖了这一点。您需要导入 <Switch> 组件,然后您可以完全删除 path 属性。

A <Switch> 呈现匹配的第一个孩子 <Route> 。没有路径的 <Route> 始终匹配

这是使用的示例:

 <Router>
  <div>
    <Switch>
      <Route path="/" exact component={Home}/>
      <Redirect from="/old-match" to="/will-match"/>
      <Route path="/will-match" component={WillMatch}/>
      <Route component={NoMatch}/>
    </Switch>
  </div>
</Router>

因此,在您的情况下,您只需删除 path="*" 并引入 <Switch>

 <Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/user" component={User}/>
  <Route component={Notfound} />
</Switch>

请记住在顶部的 import 语句中包含 Switch

原文由 James Donnelly 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是我的两个组件的解决方案。

 const NotFound = () => <div>Not found</div>

const NotFoundRedirect = () => <Redirect to='/not-found' />

//root component
<Switch>
 <Route path='/users' component={UsersPages} />
 <Route path='/not-found' component={NotFound} />
 <Route component={NotFoundRedirect} />
</Switch>

//UsersPages component
<Switch>
 <Route path='/home' component={HomePage} />
 <Route path='/profile' component={ProfilePage} />
 <Route component={NotFoundRedirect} />
</Switch>

这对我来说很完美。谢谢。

原文由 Eduin Garcia Cordero 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进