运行 仅当用户从 url 栏访问网站时才会显示动画

Run animation only when user access the website from the url bar

我想 运行 仅当用户从 url 栏
访问网站时播放动画 而不是当路线改变时。

这是我目前的解决方案

import React from 'react';
import Router from "next/router";

class Layout extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      oAni: true
    };
    this.routeChangeEnd = this.routeChangeEnd.bind(this);

  }

  componentDidMount(){
    Router.events.on('routeChangeComplete', this.routeChangeEnd);
  }
  componentWillUnmount() {
    Router.events.off('routeChangeComplete', this.routeChangeEnd);
  }
  routeChangeEnd() {
    this.setState({oAni: false});
  }
    render (){
      return (
        <>
          <OpeningAnimation st={this.state.oAni ? "flex" : "none"} aniEnd={()=>{this.setState({oAni: false})}} />

          <div>
            {this.props.children}
          </div>
          </div>
        </>
      );
    }
}

动画结束时触发aniEnd。 但这有时会导致 memory leak

仅当从 url 栏访问网站时才触发动画的最佳解决方案是什么?

为了检查用户是否完成了 SSR(服务器端渲染),换句话说,刷新页面并在 URL 栏中输入,您可以通过在 getInitialProps 中检查它来查找这个:

static async getInitialProps({req}){
  if(req){
  // Called on server
  // Here you can set a variable true
  // Later on on the code if this variable is true, then trigger the animation
  } else {
    // Called on client
  }
 }

这就是你需要做的。