在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和随机生成的会话ID(随机基数64整数),当我使用{{3}中的Router
组件时,执行此操作的最佳方法是什么} 1.0.0版。
答案 0 :(得分:0)
此问题https://stackoverflow.com/a/44410281/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>
}
}
添加location
后,请使用props
属性中的react-router
属性。测试一下每次更新是否已更改-如果已更新,则可以发送。