我有几个按钮用作路线。每次更改路线时,我都想确保处于活动状态的按钮发生更改。
有没有办法在反应路由器 v4 中监听路由变化?
我withRouter用来获取location道具。当组件因新路由而更新时,我检查值是否更改:
withRouter
location
@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> } }
希望能帮助到你