[英]ReactJS: How to make a component call a method only the very first it is rendered?
我希望組件僅一次調用方法,並且僅在組件第一次被調用時才調用方法。 我在constructor()
嘗試過它,以為它應該只發生一次,並且只有在第一次掛載時才會出現,但是看起來只要該組件再次被渲染, constructor()
也會被再次調用。
有沒有一種方法可以讓組件僅在第一次渲染時才調用方法?
謝謝
componentWillMount()
被稱為預渲染,並且只有一次,直到頁面刷新。
https://facebook.github.io/react/docs/react-component.html#componentwillmount
在render()之后立即調用componentDidMount()
,並且DOM現在可用。 這只會在第一次加載時發生,直到頁面刷新為止。
https://facebook.github.io/react/docs/react-component.html#componentdidmount
您可以使用getDerivedStateFromProps並在導航時傳遞一個空參數,該參數在導航后觸發一次。
// caller
this.props.navigation.navigate('SOMEWHERE', {})
// SOMEWHERE
static getDerivedStateFromProps(nextProps, prevState){
doSomething()
return null
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.