React router v4 route onchange事件

Anu*_*ain 3 reactjs react-router react-redux react-router-v4

有什么方法可以在路由器使用react路由器v4进行更改时触发事件.我需要在每次路线更改时触发一个功能.我在通用react-redux应用程序中使用BrowserRouterSwitch来自react-router-dom客户端.

小智 7

我通过使用其他组件包装我的应用程序来解决这个问题 该组件用于一个Route所以它也可以访问history道具.

<BrowserRouter>
  <Route component={App} />
</BrowserRouter>
Run Code Online (Sandbox Code Playgroud)

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
  }
}
Run Code Online (Sandbox Code Playgroud)

不确定这是否是在V4中执行此操作的正确方法,但我没有在路由器本身上找到任何其他扩展点,因此这似乎有效.希望有所帮助.

编辑:也许您也可以通过包装<Route />自己的组件并使用类似componentWillUpdate检测位置更改的内容来实现相同的目标.


Ukr*_*Ukr 5

反应:v15.x,反应路由器:v4.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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

索引.js:

import App from 'components/core/App';

render(<App />, document.querySelector('#root'));
Run Code Online (Sandbox Code Playgroud)