React路由器:记录到特定路线的所有访问



在react中,我有这样的代码:

<Router basename='/app'>
  <main>
    <Menu active={menu} close={this.closeMenu} />
    <Overlay active={menu} onClick={this.closeMenu} />
    <AppBar handleMenuIcon={this.handleMenuIcon} title='Test' />
    <Route path='/customers/:id' component={Customers} />
    <Route path='/products/:id' component={Products} />
  </main>
</Router>

每次访问/customers/:id/products/:id时,我都想通过对后端服务进行AJAX调用来记录访问。我将要记录的字段包括推荐子URL,当前URL和随机生成的会话ID(随机基础64个整数),当我使用react-router版本1.0.0的Router组件时,最好的方法是什么。

这已经回答了这个问题https://stackoverflow.com/a/4444410281/5746996

但本质上:

@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>
  }
}

添加react-router时,请使用props属性中的location属性。测试以查看每个更新是否已更改 - 如果有,则可以发送。

最新更新