React Router v4全局与嵌套路由子项不匹配

问题描述 投票:2回答:2

当我在React Router V4中嵌套路由时,如何将用户重定向到NoMatch组件?

这是我的代码:

import React from 'react';
import ReactDOM from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();

import {
    BrowserRouter as Router,
    Route,
    Switch
}
from 'react-router-dom';
import Website from './website/Website';

const Register = ({ match}) => {
    return (
        <div>
            <Route exact path={match.url} render={() => {return <h1>Register</h1>} } />
            <Route path={`${match.url}/detail`} render={()=>{return <h1>Register Detail</h1>}} />
        </div>
    )
}

const App = () => (
    <Router>
        <Switch>
                <Route exact path="/" render={() =>  {return <h1>Home</h1> }} />
                <Route path="/register" component={Register} />
                <Route component={() => {return <h1>Not found!</h1>}} />
        </Switch>
    </Router>
);

ReactDOM.render(
    <App/>, document.getElementById('root'));

如您所见,Register下面有一条NoMatch路由,但我不想在我的子组件Register上使用相同的Route映射。这样,如果我转到/ register / unregisteredmatch,页面只显示空白,因为不要输入NoMatch Route。

如何在未指定子路径的情况下映射全局NoMatch?我不想将此责任传递给子组件。

谢谢。

javascript reactjs nested-routes react-router-v4 no-match
2个回答
0
投票

我对Switch有同样的问题,因为如果我不去/ a,下面的代码总会呈现我的NoMatch组件

<Router history={history}>
  <Switch>
    <Route path='/a' component={A} />
    <Switch>
      <Route path='/b' component={B} />
      <Route path='/b/:id' component={C} />
    </Switch>
    <Route path="*" component={NoMatch}/>
  </Switch>
</Router>

但是,如果您在嵌套的Switch中移动NoMatch,它将按预期工作:

<Router history={history}>
  <Switch>
    <Route path='/a' component={A} />
    <Switch>
      <Route path='/b' component={B} />
      <Route path='/b/:id' component={C} />
      <Route path="*" component={NoMatch}/>  
    </Switch>
  </Switch>
</Router>

即使这是问题的“解决方案”,也不是你想要的,因为第二个Switch在不同的文件中,就像第一个路由一样。

因此,随着应用程序的增长以及更多路由在不同文件中发挥作用,您永远不知道需要将NoMatch路由放在何处以使其按预期工作。

你有没有找到解决这个问题的其他办法?


-1
投票

您可以做的是在根应用程序中定义所有可能允许的路由。因此,使用可选模式调整App组件,如下所示:

const App = () => (
    <Router>
        <Switch>
                <Route exact path="/" render={() =>  {return <h1>Home</h1> }} />
                <Route path="/register/(detail)?" exact component={Register} />
                <Route component={() => {return <h1>Not found!</h1>}} />
        </Switch>
    </Router>
);
© www.soinside.com 2019 - 2024. All rights reserved.