【问题标题】:Mobile Safari IOS will scroll bottom page automatically when reloading pageMobile Safari IOS 重新加载页面时会自动滚动底部页面
【发布时间】:2019-02-05 13:20:22
【问题描述】:

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

我正在努力寻找这个错误的来源,但我不知道。

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

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】:

    我终于找到了我在 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()在我的路由中的所有嵌套组件之前被调用。我通过在导出默认值中添加translate解决了第一个问题。

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

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

    我只需要添加

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

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

    AppContainer

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-27
      • 1970-01-01
      相关资源
      最近更新 更多