研究下react-route的源碼找到如何正確分離route配置的方法

背景

因爲我但願每一個子項目管理本身的route,因而想維護一個route的component在各個子目錄中,在index.js中import各個子項目的route.
以此簡化index.js中的須要import的依賴數量。javascript

react-route是如何配置規則的

舉個例子:java

<Router history={browserHistory}>
    <Route path='/' component={Layout}>
      <Route path='signup' component={SignupPage} />
    </Route>
  </Router>

Router組件在componentWillMount時會嘗試加載children中的Route配置, 經過遍歷children,找到他們的props, 而後把props加入route數組中。
也就是說Route組件實際上做爲一個配置用的組件,會直接被Router讀取,因此Route也沒有實際意義上的render方法。react

ps.這提供給我一個思路,如何一個組件的配置太過於多和複雜,那麼能夠搞出個專門用來作配置用的子組件,在渲染前讀取子組件的配置,加載成本身的配置。這樣的好處是大大提升了可讀性。讓配置成爲聲明而不是運算。數組

/**
 * Creates and returns a routes object from the given ReactChildren. JSX
 * provides a convenient way to visualize how routes in the hierarchy are
 * nested.
 *
 *   import { Route, createRoutesFromReactChildren } from 'react-router'
 *   
 *   const routes = createRoutesFromReactChildren(
 *     <Route component={App}>
 *       <Route path="home" component={Dashboard}/>
 *       <Route path="news" component={NewsFeed}/>
 *     </Route>
 *   )
 *
 * Note: This method is automatically used when you provide <Route> children
 * to a <Router> component.
 */

function createRoutesFromReactChildren(children, parentRoute){...}

爲何不能用一個wrapper組件來隱藏子route的細節

有了上面的知識後,這個問題就顯而易見了,由於配置是經過讀取children的props來加載的。在children外包裹一層wrapper會致使讀到wrapper的propsreact-router

怎麼實現我想要的功能

最簡單的方法就是寫個函數來直接return route。這樣既達到了分割的目的,也不會加入中間層。app

爲何一開始會想用wrapper呢

一開始不夠了解react-route的原理,覺得只要能渲染出來,效果是同樣的。ide

SO 相關問題連接

點我函數

相關文章
相關標籤/搜索