我有一些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
變量被設置爲空數組所以扔的錯誤?
釘釘!謝謝安德魯 – Stretch0