Javascript 在react native中,componentDidMount和componentDidUpdate之间有什么区别
我无法理解Javascript 在react native中,componentDidMount和componentDidUpdate之间有什么区别,javascript,react-native,Javascript,React Native,我无法理解componentDidMount和componentdiddupdate 我看到一些计数器应用程序使用setState方法来增加componentDidMount中的计数值,那么如果我们在componentdiddupdate中写入setState呢 我们应该在什么时候使用componentDidMount或componentdiddupdate?来自: componentDidMount():在装入组件(插入到DOM树中)后立即调用 componentDidUpdate(prev
componentDidMount
和componentdiddupdate
我看到一些计数器应用程序使用setState
方法来增加componentDidMount
中的计数值,那么如果我们在componentdiddupdate
中写入setState呢
我们应该在什么时候使用componentDidMount
或componentdiddupdate
?来自:
:在装入组件(插入到DOM树中)后立即调用componentDidMount()
:在更新发生后立即调用。初始渲染时不调用此方法。当组件被更新时,利用这个机会在DOM上进行操作componentDidUpdate(prevProps、prevState、snapshot)
componentdiddupdate
内部使用setState
:小心!使用setState
调用componentdiddupdate
,因此,如果在*每次调用componentdiddupdate
时调用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;
从“React”导入React;
类示例扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
计数:0
};
}
componentDidMount(){
//此函数将在初始渲染时调用。
document.title=`您单击了${this.state.count}次';
}
componentDidUpdate(){
document.title=`您单击了${this.state.count}次';
}
render(){
返回(
您单击了{this.state.count}次
this.setState({count:this.state.count+1})}>
点击我
)
}
}
导出默认示例;
您可以通过评论和取消评论这两种生命周期方法来理解。这两种方法的可能重复之处在于