在React Next.js中如何在状态更改时停止文本闪烁

时间:2019-06-09 02:29:05

标签: javascript reactjs next.js

我想在路线更改上实现一个预加载器,并带有数量虚假的加载进度。但是,loadingPercentage的文本会随着状态的变化而闪烁/闪烁。

下面是代码:

//__app.js

constructor(props) {
    super(props);

    this.state = {
      isRouteChangeStart: true,
      loadingPercentage: 0
    };
}

componentDidMount() {
    const loadingDuration = 30;
    let initialLoadTimeourEvent = null;

    if (initialLoadTimeourEvent) {
      clearTimeout(initialLoadTimeourEvent);
    }

    // Initial page loader as there are no Router events
    // during initial page load

    initialLoadTimeourEvent = setTimeout(() => {
      const initialLoadSpinnerInterval = setInterval(() => {
        this.setState(prevState => ({
          loadingPercentage: prevState.loadingPercentage + 3
        }));

        if (this.state.loadingPercentage >= 99) {
          clearInterval(initialLoadSpinnerInterval);

          this.setState({
            loadingPercentage: 0,
            isRouteChangeStart: false
          });
        }
      }, loadingDuration);
    }, 1000);

    // When the user navigates to the different route after the first load

    Router.events.on('routeChangeStart', () => {
      let spinnerInterval = null;

      this.setState({ isRouteChangeStart: true, loadingPercentage: 0 });

      if (spinnerInterval) {
        clearInterval(spinnerInterval);
      }

      setTimeout(() => {
        spinnerInterval = setInterval(() => {
          this.setState(prevState => ({
            loadingPercentage: prevState.loadingPercentage + 3
          }));

          if (
            this.state.loadingPercentage >= 99 ||
            this.state.loadingPercentage === 99
          ) {
            clearInterval(spinnerInterval);
          }
        });
      }, 400);
    });

    // When route change is completed

    Router.events.on('routeChangeComplete', () => {
      this.setState({
        isRouteChangeStart: false,
        loadingPercentage: 0
      });
    });
  }

查看

<div>
  {this.state.isRouteChangeStart && (
    <div>
      {this.state.loadingPercentage} %
    </div>
  )}
</div>

非常感谢...

0 个答案:

没有答案