【问题标题】:Preact lifecycle methods not trigger correclty in safariPreact 生命周期方法不会在 Safari 中触发正确性
【发布时间】:2019-05-21 14:31:56
【问题描述】:
  • 当改变一个组件的状态然后改变 url 时,preact 组件没有卸载
  • 问题是 IE 和 safari 特有的
  • 使用浏览器的“返回”功能时,componentDidMount 不触发,state 未设置为初始值

这是一个例子,你可以在本地运行以获得更好的理解。

 <html>
        <head>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/preact/8.4.2/preact.js"></script>
            <script src="https://unpkg.com/babel-standalone@6.26.0/babel.min.js"></script>  
        </head>
        <body>
            <div id="app"></div>
            <script type="text/babel">
              const React = preact;
              class Foo extends React.Component {
                state = {
                  loading: false
                }

                componentDidMount() {
                  console.log('mounted');
                }

                leave() {
                  this.setState({
                    loading: true
                  });
                  setTimeout(() => {
                    window.location.href = 'https://github.com/';
                  }, 2000);
                }
                
                render() {
                  return this.state.loading ? <div>loading...</div> : <button onClick={this.leave.bind(this)}>leave</button>;
                }
              }

              React.render(
                <Foo />,
                document.getElementById('app')
              );
            </script>
        </body>
    </html>
  • 点击按钮
  • 等待重定向
  • 返回
  • 页面仍然显示:“正在加载...”

返回时重置状态的最佳解决方案是什么?

【问题讨论】:

  • 我会说使用componentWillUnmount 并重置状态。但在页面导航上,它似乎没有触发该生命周期方法。
  • 这就是问题所在

标签: safari preact


【解决方案1】:

我发现这个问题与 safari back-forward cache 有关。上述问题的解决方案是监听 pageshow 事件,然后检查加载的页面是否被缓存。

componentDidMount() {
  window.addEventListener('pageshow', (event) => {
    // fix for safari cached page
    if (event.persisted) {
      this.setState({
        isLoading: false
      });
    }
  });
}

编辑:pageshow 事件仅触发一次,这是已知的webkit bug。为避免这种情况,您实际上必须使用window.location.reload() 来重置所有内容。这样事件下次会再次触发。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多