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

问题描述 投票:0回答:1

我正在使用反应,一旦我在safari上重新加载页面,它将无缘无故地在页面底部自动滚动。此错误仅在使用Iphone时出现。

我很难找到这个bug的来源,但我不知道。

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

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

使用window.scrollTo(0, 0)in componentDidMount()没有任何效果,除非我使用setTimeout,但我不知道这是正确的方法来做到这一点..

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

javascript ios iphone reactjs mobile-safari
1个回答
0
投票

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

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

routes.js

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

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

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

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

这意味着每次安装一个子项时,它将等待在渲染之前加载所有语言环境,而AppContainert则不是这样,这就是为什么他的componentDidMount首先被调用的原因。

我只需要添加

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

现在修复了生命周期,我只需要在componentDidMountin AppContainer上添加scrollBy,这次我使用了

AppContainer

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

而不是大约800ms的时间。

希望它能帮助遇到同样问题的人。

© www.soinside.com 2019 - 2024. All rights reserved.