2016-06-21 29 views
1

我正在使用react-router(2.4.1),我有一個通配符(path =「*」)後備路由來顯示「未找到」組件。可以驗證react-router <Route />組件的url參數嗎?

我的一個途徑是這樣定義:

<Route path="/campaigns/:category" component={CampaignsPage} /> 

我可以驗證category路線PARAM以任何方式檢查,如果這個類別中我的類別列表中存在?如果不是,我希望路由器可以下降到通配符以顯示未找到組件

+0

我看到一個建議,在他們的github問題中使用'url-matcher':https://github.com/reactjs/react-router/issues/2286#issuecomment-158692205 –

+0

目前似乎只有「hacky」實現這一點的方法。反應路由器開發者提到,這可能會在不久的將來實施。 – Chris

回答

0

也許您可以驗證'campaign'組件內收到的參數?沿線的東西:

class CampaignsPage extends Component { 
    render() { 
     const validCampaignCats = [...] 
     const receivedCampaignCat = this.props.params.category 

     const renderChild = (actualCat, validCats) => { 
      if (!validCats.includes(actualCat)) { 
       return <YourErrorPage/> 
      } 
      return this.props.children 
     } 

     return (
      <div> 
       <Header/> 
       { renderChild(receivedCampaignCat, validCampaignCats) } 
       <Footer/> 
      </div> 
     ) 
    } 
} 

希望幫助!

相關問題