React Native中componentDidMount和componentDidUpdate有什么区别?

15

我不明白componentDidMountcomponentDidUpdate之间的区别。

我看到一些计数器应用程序在componentDidMount中使用setState方法来增加计数值,那么如果我们在componentDidUpdate中写入setState会发生什么?

我们应该在什么情况下使用componentDidMountcomponentDidUpdate


6
可能是componentDidUpdate vs componentDidMount的重复问题。 - Andrew
2
这就是文档的用途。 - Jonny Rathbone
2个回答

34

根据组件生命周期文档:

  • componentDidMount(): 在组件被挂载到 DOM 树后立即调用
  • componentDidUpdate(prevProps, prevState, snapshot): 在组件更新后立即调用。但不会在初始渲染时调用。当组件更新后,使用此方法操作 DOM。

简单来说,第一个函数在开始时调用,而第二个函数在每次改变后调用。它们绝对不能互换使用。

关于在componentDidUpdate内部使用 setState 的问题:请注意!使用setState会调用componentDidUpdate,如果您在每次调用componentDidUpdate时都调用setState ,您可能会陷入无限循环中。

顺带一提,这里有一个很棒的图表总结了整个组件生命周期。


3

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;

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接