简体   繁体   English

ReactJS:如何使组件仅在呈现它的第一时间调用方法?

[英]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. 我在constructor()尝试过它,以为它应该只发生一次,并且只有在第一次挂载时才会出现,但是看起来只要该组件再次被渲染, constructor()也会被再次调用。

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. componentWillMount()被称为预渲染,并且只有一次,直到页面刷新。

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

componentDidMount() gets called immediately after render() and the DOM is available at this time. 在render()之后立即调用componentDidMount() ,并且DOM现在可用。 This will happen only the first time it's loaded until the page refreshes. 这只会在第一次加载时发生,直到页面刷新为止。

https://facebook.github.io/react/docs/react-component.html#componentdidmount 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. 您可以使用getDerivedStateFromProps并在导航时传递一个空参数,该参数在导航后触发一次。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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