window.addEventListener 当 scrollY 不为 0 时,路由更改时不更新状态

window.addEventListener not updating state on route change when scrollY is not 0

我正在使用 componentDidMount 中的 addEventListener 通过 setState 添加 classheaderscrollingstate 设置为 scrollY0 处的 false,滚动后,state 更新为 true并添加了 class

举个例子

componentDidMount() {
  window.addEventListener('scroll', this.handleScroll);
}

componentWillUnmount() {
  window.removeEventListener('scroll', this.handleScroll);
}

handleScroll = () => {
  if (window.scrollY === 0 && this.state.scrolling === true) {
    this.setState({ scrolling: false });
  } else if (window.scrollY !== 0 && this.state.scrolling !== true) {
    this.setState({ scrolling: true });
  }
};

在 GatsbyJS 中 layout。当用户返回到页面顶部时,它在页面和模板之间完美地工作。

但是,在某些情况下,例如 route 通过 modal 更改或用户在浏览器上返回操作是保持先前的 scrollY 位置。

在这种情况下 scrollY 不是 0scrollingstate 仍然显示 false。我想这是因为即使 scrollY 显示的是实际位置,但 state scrolling 最初是 false 直到用户滚动。 console

中对此进行了描述

如果 scrollY 不是 0,我如何确保在路由更改时,state scrolling 更新为 true

您应该 运行 您的 handleScroll 方法在实例化时捕获初始状态。现在您依赖于滚动位置在最顶部,但正如您所发现的,返回历史记录会导致不同的初始状态。

componentDidMount() {
  window.addEventListener('scroll', this.handleScroll);
  this.handleScroll();
}