【问题标题】:Scroll Restoration on location.pathname change?在 location.pathname 更改时滚动恢复?
【发布时间】: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


【解决方案1】:

你应该使用useEffect钩子调用scrollTo方法

  useEffect(() => {
    document.querySelector("#root").scrollTo(0, 0);
  }, []);

【讨论】:

    猜你喜欢
    • 2019-08-02
    • 2022-01-21
    • 1970-01-01
    • 2012-11-26
    • 2015-02-28
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    相关资源
    最近更新 更多