人们总是说你可以在componentDidMount中获取dom。
这是否意味着componentDidMount和DOMContentLoaded是同步的,或者意味着当componentDidMount执行时,dom总是准备好了?
这是否意味着componentDidMount和DOMContentLoaded是同步的,或者意味着当componentDidMount执行时,dom总是准备好了?
DOMContentLoaded
事件仅在整个HTML页面载入时触发,因此这个事件只会在整个网页的生命周期中触发一次且仅一次。componentDidMount
被调用时,React组件被渲染。因此,componentDidMount
可以被调用多次,但是是针对完全不同的相同组件类的实例。而且,在componentDidMount
事件被调用时,浏览器的DOM总是处于“准备就绪”状态。React的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);
});
DOMContentLoaded
和componentDidMount
之间的区别。 - Lin Du