2017-04-20 233 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'));