admin管理员组

文章数量:1279124

I would like for a ponent to call a method only once, and only the very first time the ponent 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 ponent is rendered again, the constructor() is called again as well.

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

Thank you

I would like for a ponent to call a method only once, and only the very first time the ponent 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 ponent is rendered again, the constructor() is called again as well.

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

Thank you

Share Improve this question asked Nov 3, 2016 at 22:21 user2426823user2426823
Add a ment  | 

3 Answers 3

Reset to default 4

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

https://facebook.github.io/react/docs/react-ponent.html#ponentwillmount

ponentDidMount() 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-ponent.html#ponentdidmount

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
   }

You could set a variable in localStorage when you first load your page. Then, whenever you render, you simply get and test that variable:

   async ponentDidMount() {
      ...
      if(localStorage.getItem('reRender') !== "true") {
          //Processing to do only for the very first render 
          localStorage.setItem('reRender', "true");
      }
   }

You could reset the variable depending on your use case afterwards (for example when logging out):

localStorage.removeItem('reRender');

本文标签: javascriptReactJS How to make a component call a method only the very first it is renderedStack Overflow