2016-10-11 52 views
1

我正在使用react-router-redux,我試圖更新我的應用程序的標題,從商店收到它的狀態,每當路線更改(@@router/UPDATE_LOCATION同步還原存儲與反應路由器路由位置(路由更改時更新標頭)

在目前我派遣行動componentWillMount這樣的:

componentWillMount() { 
    this.props.appActions.setHeader('New Block') 
    } 

當我手動設置頁眉中componentWillMount在路線/blocks/new,它是一個路線「塊」的孩子,誰都有一個不同的標題,當我回到history時它不起作用,因爲th路由blocks的e組件不會再次掛載,而是掛載仍然。因此,標題仍然是New Block。而不是自己的標題之前,當安裝blocks,並且new仍然作爲孩子卸載。

(當我嘗試逆時redux-devtools,什麼似乎我每次回去的地方,一個組件再次安裝的時間,這時再發生,它會再次派遣行動,以及devtool將收到另一調度)

的路線:

<Route path="begin" component={PlayerBeginContainer}> 
    <IndexRoute component={PlayerOverview}/> 
     <Route path="blocks" component={PlayerBlocks}> 
     <Route path="new" component={PlayerNewBlock}/> 
     </Route> 
</Route> 
... 

我試圖同步店裏當路由變化,但:

if (action && action.type === UPDATE_LOCATION) { 
let path = action.payload.pathname.split('/') 
// Laboriously iterate through array to figure out what the new header state should be. 
    // i.e. if (1 in split && split[1] === 'routeName') 
    // or let lastPath = path[path.length - 1] 
    // and getting parentPath would require more checking of whether it is the parent itself or not etc. 
    // appHeader = 'routeHeader' 
    return Object.assign({}, state, { appHeader: appHeader}); 
} 

當你只需要它在特定的子路由上觸發時,這會變得非常單調乏味, 我想避免再創建另一個嵌套結構,而我已經在路由器中定義了它。

在頭文件中,我不能使用除this.props.location.pathname以外的其他任何東西來嘗試找出我正在使用的路線,並且組件本身不應該自行設置標頭(即在componentWillMount)。

最後的選擇是使用路由器onEnter,但我想保持路由器的清潔,但也許我需要妥協。

有什麼我在這裏失蹤?或者某種類型的lib可以幫助我呢?

TL; DR:如何讓我的header組件知道我們正在使用哪條路線,而不必分解location.pathname以找出我們的位置?

+0

你可以得到的整個位置狀態作爲您的''mapStateToProp''中相關響應組件的通道,方法是獲取您已給予'react-router-redux''的狀態的位置片段。一旦你擁有它作爲道具,你應該能夠做你想做的。它可能最終會再次拆分路徑名,但它似乎比收聽UPDATE_LOCATION動作更清晰。 – iamnat

+0

這是否有幫助:https://github.com/reactjs/react-router-redux#how-do-i-access-router-state-in-a-container-component? – iamnat

+0

@iamnat,事情是,我沒有使用'params.id'或'query.filter',所以我的頭仍然需要'.split('/')'每個案例的路徑名。 – BlockChange

回答

0

這是我的一個代碼庫中的代碼。在這個應用程序中我使用哈希歷史,但我認爲你也可以用other history objects做同樣的事情。

import {hashHistory} from 'react-router'; 
import {syncHistoryWithStore} from 'react-router-redux'; 

const history = syncHistoryWithStore(hashHistory, store); 
history.listen(location => { 
    // here you can do something after location is updated 
}); 

<Router history={history}> 
.... 
</Router> 

,然後在你的組件,你可以從state.routing一些信息:

function mapStateToProps(state) { 
    return { 
    current: state.routing.locationBeforeTransitions.pathname, 
    }; 
} 

export default connect(mapStateToProps)(App); 

從某些成分改變路線,這樣做:

import {push} from 'react-router-redux'; 
this.props.dispatch(push('/route'));