我不明白componentDidMount
和componentDidUpdate
之间的区别。
我看到一些计数器应用程序在componentDidMount
中使用setState
方法来增加计数值,那么如果我们在componentDidUpdate
中写入setState
会发生什么?
我们应该在什么情况下使用componentDidMount
或componentDidUpdate
?
我不明白componentDidMount
和componentDidUpdate
之间的区别。
我看到一些计数器应用程序在componentDidMount
中使用setState
方法来增加计数值,那么如果我们在componentDidUpdate
中写入setState
会发生什么?
我们应该在什么情况下使用componentDidMount
或componentDidUpdate
?
根据组件生命周期文档:
componentDidMount()
: 在组件被挂载到 DOM 树后立即调用 componentDidUpdate(prevProps, prevState, snapshot)
: 在组件更新后立即调用。但不会在初始渲染时调用。当组件更新后,使用此方法操作 DOM。简单来说,第一个函数在开始时调用,而第二个函数在每次改变后调用。它们绝对不能互换使用。
关于在componentDidUpdate
内部使用 setState
的问题:请注意!使用setState
会调用componentDidUpdate
,如果您在每次调用componentDidUpdate
时都调用setState
,您可能会陷入无限循环中。
顺带一提,这里有一个很棒的图表总结了整个组件生命周期。
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;
您可以通过注释和取消注释生命周期方法来理解。