React router v4路由更改事件

4

在使用React Router v4时,是否有方法可以在路由更改时触发事件?我需要在每次路由更改时执行一个函数。我在通用的React-Redux应用程序中在客户端使用BrowserRouterSwitch来自react-router-dom


1
新的V4 API不再有onEnter方法,所以在这里无法使用。 - Dennis
2个回答

10

我通过在我的应用程序周围包装一个额外的组件来解决了这个问题。该组件在一个 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包的history.createBrowserHistory方法吗? - Anurag Jain
1
@Dennis 这不是我预期的,但我很满意,谢谢。 - JoxieMedina
componentWillMount()中有一个bug。应该是: const { history } = this.props.router; - TasDiam

5

React: v15.x, React Router: 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'));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接