2017-06-02 129 views
0

只有當產品存在於我的JSON文件中時,我纔想將請求重定向到/work/:product。目前,我有以下幾點:檢查路由是否存在

<Route path="/work/:product"render={props => (check_that_product_exiists) ? <Life sayHello = { this.sayHello } />:<Redirect to="/" />} /> 

的產品名稱目前具有此模式的JSON文件:

[ 
    { 
     "name":"adcall", 
     ... 
    }, 
    ... 
] 

我如何檢查佔位符產品中的要素之一嵌套的JSON文件?我正在使用react-router v4(與之前的版本有點不同)。

回答

0

就我個人而言,我不會在路由器級別做它,但在組件級別。因此,允許用戶經歷:

<Route 
    path="/work/:product" 
    render={Life} 
/> 

然後在你的Life組件,你可以做

... 
componentWillMount() { 
    if (isProductExisting === false) 
    window.location = '/'; 
} 
... 

爲什麼我這樣做是在componentWillMount的原因是因爲我想避免的元件安裝如果當時我我要重定向。在此組件中,您可以從導入的JSON文件中抓取產品名稱,並從路徑中獲取產品名稱(確保在此情況下使用withRouter方法將路由選擇傳遞到此組件)。