当我在 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?我不想将此责任传递给子组件。
谢谢。
最佳答案
我对 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>
但是,如果您像这样将 NoMatch 移动到嵌套的 Switch 中,它将按预期工作:
<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 与第一个 Route 一样位于不同的文件中.
因此,随着应用程序的增长和更多路由在不同文件中发挥作用,您永远不知道需要将 NoMatch 路由放在哪里才能使其按预期工作。
您是否找到了解决此问题的其他方法?
关于javascript - React Router v4 全局不匹配嵌套路由子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43289132/