人们总是说你可以在dom
中获得componentDidMount
。
这意味着componentDidMount
和DOMContentLoaded
是同步的,还是意味着componentDidMount
,dom
总是准备就绪?
答案 0 :(得分:8)
当entire HTML page loads时,DOMContentLoaded
事件独占。因此,此事件仅在整个网页的生命周期内被触发一次且仅一次。另一方面,componentDidMount
在呈现React组件时被调用。因此,componentDidMount
完全有可能被调用多次,尽管对于同一组件类的完全不同的实例。
是的,在调用componentDidMount
事件时,浏览器的DOM始终处于“就绪状态”。
答案 1 :(得分:8)
在componentDidMount
之前触发DOMContentLoaded
反应,并且DOM已准备就绪。
在此演示中查看控制台日志:http://codepen.io/PiotrBerebecki/pen/EgdkXB
记录以下内容:
componentDidMount: React rendered!
DOMContentLoaded before class: React rendered!
DOMContentLoaded after class: React rendered!
DOMContentLoaded in constructor: React rendered!
DOMContentLoaded in render: React rendered!
DOMContentLoaded in componentDidMount: React rendered!
DOMContentLoaded after ReactDOM.render: React rendered!
完整代码:
document.addEventListener('DOMContentLoaded', function(event) {
console.log('DOMContentLoaded before class:', document.getElementById('app').textContent);
});
class App extends React.Component {
constructor() {
super();
document.addEventListener('DOMContentLoaded', function(event) {
console.log('DOMContentLoaded in constructor:', document.getElementById('app').textContent);
});
}
componentDidMount() {
document.addEventListener('DOMContentLoaded', function(event) {
console.log('DOMContentLoaded in componentDidMount:', document.getElementById('app').textContent);
});
console.log('componentDidMount:', document.getElementById('app').textContent);
}
render() {
document.addEventListener('DOMContentLoaded', function(event) {
console.log('DOMContentLoaded in render:', document.getElementById('app').textContent);
});
return (
<div>
React rendered!
</div>
);
}
}
document.addEventListener('DOMContentLoaded', function(event) {
console.log('DOMContentLoaded after class:', document.getElementById('app').textContent);
});
ReactDOM.render(
<App />,
document.getElementById('app')
);
document.addEventListener('DOMContentLoaded', function(event) {
console.log('DOMContentLoaded after ReactDOM.render:', document.getElementById('app').textContent);
});