React Router "on change" 事件?

ReactRouter "on change" event?

我想在我的单页应用程序上安装一个分析处理程序,并想捕获主路由下的每个路由更改。我知道 ReactRouter 提供了一个 onEnter 路由事件;但是,这需要我在每条路线上单独安装处理程序。我可以创建一个自动填充 onEnter 的 Route 子类,但那样我就无法覆盖 onEnter 并仍然保留分析跟踪处理程序。

监听给定根路由内任何变化的最佳方式是什么?

答案是(形象地)盯着我的脸。

当您启动路由器时,您调用 Router.run(routes, callback)。每次路由更改时都会调用回调。因此,下面的代码按照我想要的方式工作:

Router.run(routes, function (Handler) {
  doSomethingAnalytics(document.location.hash);
  React.render(<Handler/>, document.body.querySelector('#content'));
});

您可以使用 react-router willTransitionTo 静态函数来检测路由更改并在 ga() 函数调用中发出 transition.path,如下所示:

var App = React.createClass({
  mixins: [Router.State],
  statics: {
    willTransitionTo: function(transition, params, query, props) {
      ga('send', 'pageview', {'page': transition.path});
    }
  },
  render: function() {
    return (
      <div>
        <RouteHandler />
      </div>
    );
  }
});

可以在 中看到更完整的示例。

每次更改路线时都会调用此函数

const history = syncHistoryWithStore(browserHistory, store);

history.listen((location)=>{
  console.log(location)
});

反应:v15.x,反应路由器:v4.x

components/core/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'));