react如何在切换路由的时候,页面在最顶部?

vue有相关配置,但是因为用户需要,reactRouter在之前的版本中舍弃了其配置,需要用户自定义设置

方法:

创建一个组件,判断切换后的页面是否是最顶端

···

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>
);