React Native中componentdidmount和componentdidupdate有什么区别

时间:2019-02-22 23:32:47

标签: javascript react-native

我不明白组件安装和更新之间有什么区别

我看到一些计数器应用程序使用setState方法来增加componentdidmount内的计数值,所以如果我们在componentdidupdate内编写setState怎么办?

什么时候应该使用componentdidmount或componentdidupdate ????

2 个答案:

答案 0 :(得分:4)

来自the docs on the component lifecycle

  • componentDidMount():在安装组件(插入DOM树)后立即调用
  • componentDidUpdate(prevProps, prevState, snapshot):在更新发生后立即被调用。初始渲染不调用此方法。组件更新后,可以借此机会在DOM上进行操作。

为简单起见,第一个在开头被调用,第二个在每次更改时被调用。它们是绝对不能互换的。

关于在setState内部使用componentDidUpdate当心!使用setState会调用componentDidUpdate,因此,如果在每次调用setState时调用componentDidUpdate,可能会导致无限循环。

哦,还有a cool diagram,总结了整个组件的生命周期。

答案 1 :(得分:0)

componentDidMount()

componentDidMount()将在安装组件后立即呈现。此方法将仅渲染一次,并且所有需要DOM节点的初始化都应在此处进行。在此方法中设置状态会触发重新渲染。

componentDidUpdate()

每次发生更新时,都会立即调用

componentDidUpdate()。初始渲染不会调用此方法。

您可以从下面的示例中了解更多信息

import React from 'react';

class Example extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  componentDidMount() {

    //This function will call on initial rendering.
    document.title = `You clicked ${this.state.count} times`;

  }
  componentDidUpdate() {
     document.title = `You clicked ${this.state.count} times`;
   }

  render(){
    return(
      <div>
      <p>You clicked {this.state.count} times</p>
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        Click me
      </button>
    </div>
    )
  }
}
export default Example;

您可以通过注释和取消注释这两种生命周期方法来理解。