繁体   English   中英

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

[英]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.

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