简体   繁体   中英

On page refresh which life cycle method called in react?

I have page which had componentA and on componentDidMount cycle method i am updating state which trigger some animation but if I refresh the page animation doesn't play. Please let know how I can resolve this issue. below is my component code

import React from 'react';
import { findDOMNode } from 'react-dom';
import Nav from "../nav/nav-component";
class Mylist extends React.Component{
  constructor(props) {
    super(props);
    this.handleScroll = this.handleScroll.bind(this);
    this.state = { animationClass: '' , transform : 12  };
  }
  componentDidMount() {
      window.addEventListener('scroll', this.handleScroll);
      this.setState({animationClass:'animate'});
  };
  componentDidUpdate() {
      //this.setState({animationClass:''});
  };

  componentWillUnmount() {
      window.removeEventListener('scroll', this.handleScroll);
      this.setState({animationClass:''});
  };
  handleScroll(event){
    const scrollTop = event.srcElement.body.scrollTop,
          ele = findDOMNode(this.refs.toggle), // how to get dom element in react
          childElements = ele.children,
          componentTopPos = ele.getBoundingClientRect();
    //itemTranslate = Math.min(0, scrollTop/3 - 60);

    console.log("scrollTop",scrollTop);
    console.log(childElements);
    console.log("componentTopPos",componentTopPos);

     console.log(this);
    this.setState({
      transform: "dsfdf"
    });
  }
  render(){
    return ( 
      <div className={'header '+this.state.animationClass}>
      <Nav />
      </div> 
    );
  }
}
export default Mylist;

Bear in mind that componentDidMount is called only once. It doesn't matter how many times you will refresh the page. The method is not going to be called again. Better way to play the animation in my opinion is to set a flag in your local state, for instance "playAnimation: true", after the animation is played set your state to false. On refresh your state is going to become true again and the animation will play again. Hope I helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM