【发布时间】:2021-08-31 06:58:20
【问题描述】:
只有在 location.pathname 改变时页面才应该滚动到顶部,React.memo 只有在 pathname 改变而不是查询参数时才应该返回 true。但是即使应该更新返回false,页面也会滚动到顶部。
const shouldUpdate = (prevProps, nextProps) => {
return prevProps.location.pathname !== nextProps.location.pathname;
};
const ScrollToTop = ({ history }) => {
useLayoutEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
};
}, []);
return (null);
};
export default withRouter(React.memo(ScrollToTop, shouldUpdate));
<React.Fragment>
<Router>
<ScrollToTop />
<Switch>
.
.
.
</Switch>
</Router>
</React.Fragment>
【问题讨论】:
-
这是我尝试的第一个解决方案。
标签: reactjs react-router react-router-dom