2016-08-18 103 views
0

如何從<Router>onUpdate訪問this.props?我需要能夠看到目前的路線是什麼,我需要訪問this.props.route我想確定它是什麼頁面(name)。 enter image description here我找不到它的一些資源。我有這樣的代碼(現在它檢查了window.location來確定它是什麼頁面,但問題是蛞蝓,因爲它可以是任何不同的靜態頁面):react-router如何訪問this.props

const logPageViews =() => { 
    if (_.startsWith(window.location.pathname, '/search/')) { 
    let query = window.location.pathname.replace('/search/', '').replace(/--/g, '/').replace(/-/g, '+'); 
    if (!_.isEmpty(window.location.search)) { 
     query += `&${window.location.search.replace('?', '')}`; 
    } 

    ga.pageview(`/search?query=${query}`); 
    } else { 
    ga.pageview(window.location.href.replace(window.location.origin, '')); 
    } 

    fbq.pageView(); 
} 

const reducer = combineReducers(reducers); 
const store = applyMiddleware(...middlewares)(createStore)(reducer, initialState); 

ReactDOM.render(
    <Provider store={store}> 
    <Router routes={getRoutes(store)} history={browserHistory} onUpdate={() => {logPageViews()}} /> 
    </Provider>, 
    document.getElementById('app') 
); 
+0

它有助於直接調用'logPageViews'而不是將它包裝在一個匿名函數中嗎?所以:'onUpdate = {logPageViews}' –

+0

@MaartenBicknese'this'仍然沒有定義這樣做。 – index

回答

0

我有兩個可能的答案。首先,你能否潛在地訪問來自該州的當前路線,就像這裏的演示? https://github.com/reactjs/react-router/issues/1539

第二,當你調用getRoutes(store)時,你能訪問路由數組的最後一個元素嗎?

+0

首先:您的意思是https://github.com/reactjs/react-router/issues/1539#issuecomment-121499082或https://github.com/reactjs/react-router/issues/1539#issuecomment-128403889?對於第一個鏈接,我不知道'routerStateChange'是什麼,'this'在我的'onUpdate'函數中是未定義的。在第二個鏈接上,我得到'無效的'兒童'提供給'提供者',期望一個單一的ReactElement.' – index

+0

第二:我做的是'const allRoutes = getRoutes(store);'然後我得到一個所有我的數組當我做'console.log(allRoutes);'的路線 – index