2017-04-05 20 views
2

有沒有辦法指定路線處理程序來處理所有與定義的路線不匹配的路線?就像一條全路由或默認路由處理程序。如何處理不符合模式的路線

我遇到了用例,我想要加載默認頁面,如果沒有找到匹配的路線。例如,它會加載一個「頁面未找到」頁面。

回答

2

react-routerv4你可以再補充一個Route沒有path道具組件作爲最後一個在你的路由定義,如果沒有其他路由匹配將匹配:

react-router文檔

copied

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

這裏是URL路徑不是/,或/old-match/will-match部件NoMatch示出。

react-routerv3同樣的原則也適用:你剛纔只用通配符*path道具添加Route組件添加到您的路由定義的末尾:

<Router ... > 
    { /* Your actual route declarations */ } 
    <Route component={ NoMatch } path="*" /> 
</Router> 

希望這有助於!