2017-04-20 242 views
2

當路由發生變化時,有沒有什麼辦法可以觸發路由器v4。我需要在每個路線變化上開啓一個功能。我在客戶端使用和Switch,從react-router-dom開始使用universal react-redux應用程序。React路由器v4路由onchange事件

+1

新的V4 API不再具有'onEnter'方法,所以在這裏不起作用。 – Dennis

回答

3

我解決了這個問題,用附加組件包裝了我的應用程序。該組件用於Route,因此它也可以訪問history道具。

<BrowserRouter> 
    <Route component={App} /> 
</BrowserRouter> 

App組件訂閱歷史的變化,所以我可以做什麼,只要路由變化:

export class App extends React.Component { 
    componentWillMount() { 
    const { history } = this.props; 
    this.unsubscribeFromHistory = history.listen(this.handleLocationChange); 
    this.handleLocationChange(history.location); 
    } 

    componentWillUnmount() { 
    if (this.unsubscribeFromHistory) this.unsubscribeFromHistory(); 
    } 

    handleLocationChange = (location) => { 
    // Do something with the location 
    } 

    render() { 
    // Render the rest of the application with its routes 
    } 
} 

不知道這是做在V4以正確的方式,但我沒有」在路由器本身上找到任何其他可擴展性點,所以這似乎可以工作。希望有所幫助。

編輯:也許你也可以實現相同的目標,將<Route />包裝在你自己的組件中,並使用類似componentWillUpdate的東西來檢測位置變化。

+1

當我需要更改狀態更改路線時,是否可以使用歷史包中的history.createBrowserHistory方法? –

+1

@丹尼斯這不是我所期望的,但我很滿意,謝謝 – JoxieMedina

0

陣營:v15.x,陣營路由器:4.x版

組件/核心/ App.js:

import React, { Component } from 'react'; 
import PropTypes from 'prop-types'; 
import { BrowserRouter } from 'react-router-dom'; 


class LocationListener extends Component { 
    static contextTypes = { 
    router: PropTypes.object 
    }; 

    componentDidMount() { 
    this.handleLocationChange(this.context.router.history.location); 
    this.unlisten = 
this.context.router.history.listen(this.handleLocationChange); 
    } 

    componentWillUnmount() { 
    this.unlisten(); 
    } 

    handleLocationChange(location) { 
    // your staff here 
    console.log(`- - - location: '${location.pathname}'`); 
    } 

    render() { 
    return this.props.children; 
    } 
}  

export class App extends Component { 
    ... 

    render() { 
    return (
     <BrowserRouter> 
     <LocationListener> 
     ... 
     </LocationListener> 
     </BrowserRouter> 
    ); 
    } 
} 

index.js:

import App from 'components/core/App'; 

render(<App />, document.querySelector('#root'));