Mobile Safari IOS 将在重新加载页面时自动滚动底部页面

Mobile Safari IOS will scroll bottom page automatically when reloading page

我正在使用 React,只要我在 Safari 上重新加载页面,它就会无缘无故地自动滚动到页面底部。此错误 使用 Iphone 时出现。

我正在努力寻找这个错误的来源,但我没有任何线索。

我找到的唯一解决方案是:

componentDidMount() {
  setTimeout(() => {
    window.scrollTo(0, 0);
  }, 800); 
}

在 componentDidMount() 中使用 window.scrollTo(0, 0) 没有效果,除非我使用 setTimeout,但我不知道这是正确的方法..

当我从应用程序中单击 link 时,我没有遇到任何问题,因为我使用的是这种方法 https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/guides/scroll-restoration.md

我终于找到了为什么我在 Safari Mobile 上有这种不良行为。

在我的应用程序中,我有一个组件 AppContainer,它封装了我所有的路由

routes.js

 <AppContainer location={window.location}>
    <Switch>
        <Route path="/sign-in" component={SignInContainer} />
    </Switch>
</AppContainer>

其中,我默认导出 class export default withRouter((connect(mapStateToProps, mapDispatchToProps)(AppContainer)));

事实证明,在这个组件中,componentDidMount()在我的路由中的所有嵌套组件之前被调用。我通过在导出默认值中添加 translate 解决了第一个问题。

因为我使用 react-i18next 和选项 react: { wait: true }, 所有嵌套的子组件都有 export default translate(['common')).

这意味着每次安装子项时,它都会在渲染之前等待加载所有语言环境,AppContainer不是这种情况,这就是为什么首先调用他的 componentDidMount 的原因。

我只需要添加

export default withRouter( translate([])(connect(mapStateToProps, mapDispatchToProps)(AppContainer)), );

现在生命周期固定了,我只需要在 AppContainer 中的 componentDidMount 上添加 scrollBy,这次我使用

AppContainer

  componentDidMount() {
    setTimeout(() => {
        window.scrollTo(0, -5000);
    }, 0);
  }

而不是大约 800 毫秒的超时。

希望对遇到同样问题的人有所帮助。