2017-05-31 174 views
0

我有一些Route組件,我正在使用這些組件來動態生成路由,這些組件是基於CMS(我通過API訪問的)中設置的頁面使用react-router 4.我已經將這些頁面緩存,然後設置爲初始狀態便於訪問。爲什麼我的Route組件不能渲染?

我想循環瀏覽頁面集,並根據頁面設置的模板將頁面匹配到組件。

class Routes extends Component { 

    getRoutes(){ 

    const routes = map(this.props.pages, (page, key) => { 
     switch(page.template){ 
     case 'home': 
      return <Route exact path={`${page.path}`} component={Home} key={key}/> 
     case 'about': 
      return <Route path={`${page.path}`} component={About} key={key}/> 
     case 'campaign': 
      return <Route path={`${page.path}`} component={Campaign} key={key}/> 
     case 'product': 
      return <Route path={`${page.path}`} component={Product} key={key}/> 
     case 'article': 
      return <Route path={`${page.path}`} component={Article} key={key}/> 
     case 'contact': 
      return <Route path={`${page.path}`} component={Contact} key={key}/> 
     default: 
      throw new Error(`No page container matching page's template - ${page.template}`) 
     } 
    }) 

    return (
     <Switch> 
     {routes} 
     <Route component={NoMatch}/> 
     </Switch> 
    ) 
    } 

    render() { 

    const routes = this.getRoutes; 

    return (
     {routes} 
    ) 
    } 
} 

我得到一個錯誤:

Invariant Violation: Routes.render() : A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

我懷疑,因爲環需要時間來運行,該routes變量被設置爲空數組所以扔的錯誤?

回答

1

I suspect because the loop is taking time to run, the routes variable is set to an empty array so is throwing that error?

這是不正確的,循環是同步的。 routes不會爲空。

問題是你回錯了。你必須返回一個JSX元素,但你的代碼目前是:

  1. 無效JSX,內嵌JSX表達式必須有一個父元素,再加上解釋實際上是將其解釋爲({ routes })是一個無效的對象render從而錯誤消息

  2. 你的直列JSX是一個方法參考:this.getRoutes,你需要執行它的返回值:this.getRoutes()

相反,這樣做:

render() { 
    <div> 
    {this.getRoutes()} 
    </div> 
} 

所以,有一個家長到在線表達,或者你可以得到完全擺脫父爲簡潔:

render() { 
    return this.getRoutes(); 
} 

這將返回相應的<Route>組件。

+0

釘釘!謝謝安德魯 – Stretch0