4

当路由通过反应路由器 v4 更改时,有什么方法可以触发事件。我需要在每次路由更改时触发一个函数。我在通用 react-redux 应用程序的客户端使用BrowserRouterand Switchfrom react-router-dom

4

2 回答 2

10

我通过使用附加组件包装我的应用程序解决了这个问题。该组件在 a 中使用,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检测位置变化之类的东西来实现相同的目标。

于 2017-04-20T07:38:21.307 回答
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>
    );
  }
}

index.js:

import App from 'components/core/App';

render(<App />, document.querySelector('#root'));
于 2017-11-15T17:46:32.730 回答