简体   繁体   中英

ReactJS: How to make a component call a method only the very first it is rendered?

I would like for a component to call a method only once, and only the very first time the component gets rendered. I attempted it in constructor() , thinking that it is supposed to occur only once and only when it is first mounted ever, but looks like whenever that component is rendered again, the constructor() is called again as well.

Is there a way to have a component call a method only once and only the very first time it is rendered?

Thank you

componentWillMount() gets called pre-render and only once until the page refreshes.

https://facebook.github.io/react/docs/react-component.html#componentwillmount

componentDidMount() gets called immediately after render() and the DOM is available at this time. This will happen only the first time it's loaded until the page refreshes.

https://facebook.github.io/react/docs/react-component.html#componentdidmount

you can use getDerivedStateFromProps and pass an empty parameter while you navigate, that triggers the method once after the navigation.

  // caller 
     this.props.navigation.navigate('SOMEWHERE', {})

   // SOMEWHERE
  static getDerivedStateFromProps(nextProps, prevState){
    doSomething()
    return null
   }

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