2016-08-24 38 views
1

試圖瞭解react-router的基礎知識,我對選擇和選項有點不知所措。我有一個react + redux應用程序,根據Teropa's awesome tutorial提供的一般準則構建。如何在共同標題下嵌套組件

基本上我需要的是所有路線上常見的Header組件;從標題中,用戶可以單擊按鈕來更改主要組件(每個視圖提供不同的數據可視化)。這個容器還應該鏈接到redux存儲區,並讓公共數據流向下選擇的主要組件。這在我看來是一個超級共同的需要,但我不能找到一個堅實的例子/教程> _ <

到目前爲止,設立如下:

// index.jsx --> sets up the redux store and react-router routes 

const routes = <Route> 
    <Route path="/" component={AppContainer} /> 
    <IndexRoute to="/summary" /> 
    <Route path="summary" component={Summary} /> 
    <Route path="users" component={Users} /> 
    <Route path="devices" component={Devices} /> 
</Route>; 

ReactDOM.render(
    <Provider store={store}> 
    <Router history={hashHistory}>{routes}</Router> 
    </Provider>, 
    document.getElementById('app') 
); 

// App.jsx --> the main container component 

export const App = React.createClass({ 
    render: function() { 
    return <div> 
     <Header {...this.props} /> 
     {this.props.children} 
    </div>; 
    } 
}); 

function mapStateToProps(state) { 
    return state; 
} 

export const AppContainer = connect(mapStateToProps, actionCreators)(App); 

SummaryUsersDevices組件僅僅是標準的啞元React組件,它們基於數據流向進行填充。目前,收到的錯誤是那些愚蠢的組件無法訪問REDX存儲。但是,如果我將它們直接鏈接到商店,則它們在沒有Header的情況下進行渲染。

編輯:移除參照棄用<RouteHandler />

回答

2

documentation

RouteHandler不見了。現在路由器會根據活動路由自動填充組件的this.props.children 。

嘗試用

export const App = React.createClass({ 
    render: function() { 
    return <div> 
     <Header {...this.props} /> 
     { this.props.children } 
    </div>; 
    } 
}); 

你也應該解決您的路由,以便AppContainer實際上包含的其餘部件(和Redirect):

const routes = <Route component={AppContainer} /> 
    <Redirect from="/" to="/summary" /> 
    <Route path="summary" component={Summary} /> 
    <Route path="users" component={Users} /> 
    <Route path="devices" component={Devices} /> 
</Route>; 
+0

感謝您的回覆。不幸的是,主要組件,例如'Summary'仍然返回錯誤,指示它們無法訪問REDX存儲庫。有什麼想法嗎? – Kwhitejr

+1

您必須將每個組件分別連接到商店以供它們使用,無論是否使用兒童。 – martriay

+0

所以我已經將'Summary'組件連接到了商店,並且它呈現(woot),但是'Header'不......看起來像'Summary'組件獨立呈現而不考慮'App'容器外殼?當然,我可以在每個組件中包含「Header」,但是我的問題的重點是如何不在不同路線上重新渲染通用組件。 – Kwhitejr

0

如果您想訪問終極版店,那麼你必須先渲染它。要做到這一點,您必須手動執行或僅使用react-redux庫。 此外,最好放置Provider上層比路由器。

所以您最初的代碼會像:

ReactDOM.render(
<Provider store={store}> 
    {router} 
</Provider>, 
domRef 
); 

所有組件後,將有機會在context存儲。爲了避免混淆,只需使用{ connect } from 'react-redux',將組件包裹在其中並選擇所需的屬性。