如何收听反应路由器

如何收听反应路由器

本文介绍了如何收听反应路由器 v4 中的路由变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个按钮用作路由.每次更改路线时,我都想确保处于活动状态的按钮发生变化.

I have a couple of buttons that acts as routes. Everytime the route is changed, I want to make sure the button that is active changes.

有没有办法在 react router v4 中监听路由变化?

Is there a way to listen to route changes in react router v4?

推荐答案

我使用 withRouter 来获取 location 道具.当组件因为新路由而更新时,我检查值是否改变:

I use withRouter to get the location prop. When the component is updated because of a new route, I check if the value changed:

@withRouter
class App extends React.Component {

  static propTypes = {
    location: React.PropTypes.object.isRequired
  }

  // ...

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      this.onRouteChanged();
    }
  }

  onRouteChanged() {
    console.log("ROUTE CHANGED");
  }

  // ...
  render(){
    return <Switch>
        <Route path="/" exact component={HomePage} />
        <Route path="/checkout" component={CheckoutPage} />
        <Route path="/success" component={SuccessPage} />
        // ...
        <Route component={NotFound} />
      </Switch>
  }
}

希望能帮到你

这篇关于如何收听反应路由器 v4 中的路由变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 16:40