React.js,`DOMContentLoaded`是否与`componentDidMount`相等?

时间:2016-10-18 09:23:02

标签: reactjs

人们总是说你可以在dom中获得componentDidMount

这意味着componentDidMountDOMContentLoaded是同步的,还是意味着componentDidMountdom总是准备就绪?

2 个答案:

答案 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);
});