我不明白componentDidMount
和componentDidUpdate
之间有什么区别
我看到一些计数器应用程序使用setState
方法来增加componentDidMount
中的计数值,所以如果我们在componentDidUpdate
中写入setState呢?
我们什么时候应该使用componentDidMount
或componentDidUpdate
?
我不明白componentDidMount
和componentDidUpdate
之间有什么区别
我看到一些计数器应用程序使用setState
方法来增加componentDidMount
中的计数值,所以如果我们在componentDidUpdate
中写入setState呢?
我们什么时候应该使用componentDidMount
或componentDidUpdate
?
从the docs on the component lifecycle开始:
componentDidMount()
:在安装组件(插入DOM树)后立即调用componentDidUpdate(prevProps, prevState, snapshot)
:在更新发生后立即调用.初始渲染时不调用此方法.当组件被更新时,利用这个机会在DOM上进行操作.简单来说,第一个在开始时被调用,第二个在每次更改时被调用.它们绝对不能互换.
关于在componentDidUpdate
:beware内使用setState
!使用setState
次调用componentDidUpdate
,所以如果每次调用componentDidUpdate
都调用setState
次,可能会得到一个无限循环.
还有,这里有a cool diagram条总结了整个组件生命周期.