React how to switch the route, the page is at the top

Vue has related configurations, but because of user needs, reactRouter has abandoned its configuration in previous versions, and requires user-defined settings

 

method:

Create a component to determine whether the switched page is at the top

···

import React from 'react';
import {
Route,
withRouter,
} from "react-router-dom";
class ScrollToTop extends React.Component {
componentDidUpdate(prevProps, prevState, snapshot) {
if (this.props.location.pathname !== prevProps.location.pathname) {
window.scrollTo(0, 0)
}
}
render() {
return this.props.children
}
}
export default ScrollToTop;

```
然后在app中引入该组件

```
return (
<Router>
<Switch>
<ScrollToTop>
<Route path='/' exact
render={token ? () => LayEditRouter : () => <Redirect to='/login' push/>}
/>
<Route path='/login' component={Login}/>
<Route path='/' render={props => LayEditRouter}/>
</ScrollToTop>
</Switch>
</Router>
);





Guess you like

Origin www.cnblogs.com/duokexiao/p/12676380.html