【问题标题】:React router v4 route onchange event反应路由器 v4 路由 onchange 事件
【发布时间】:2017-09-16 16:05:03
【问题描述】:

当路由更改与反应路由器 v4.我需要在每次路由更改时触发一个函数。我在通用 react-redux 应用程序的客户端使用来自 react-router-domBrowserRouterSwitch

【问题讨论】:

  • 新的 V4 API 不再有 onEnter 方法,所以这在这里不起作用。

标签: reactjs react-router react-redux react-router-v4


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我通过使用附加组件包装我的应用程序解决了这个问题。该组件用于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 中执行此操作的正确方法,但我没有在路由器本身上找到任何其他可扩展点,因此这似乎可行。希望对您有所帮助。

    编辑:也许您也可以通过将&lt;Route /&gt; 包装在您自己的组件中并使用componentWillUpdate 之类的东西来检测位置变化来实现相同的目标。

    【讨论】:

    • 当我需要在状态变化时更改路由时,我可以使用 history 包中的 history.createBrowserHistory 方法吗?
    • @Dennis 这不是我的预期,但我很满意,谢谢
    • componentWillMount() 中有一个错误。应该是:const { history } = this.props.router;
    猜你喜欢
    • 2017-12-06
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    相关资源
    最近更新 更多