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 user2426823user24268233 Answers
Reset to default 4ponentWillMount()
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');
版权声明:本文标题:javascript - ReactJS: How to make a component call a method only the very first it is rendered? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741211211a2359158.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论