我对此很好奇。我在下面写了一个演示:
class ChildComponent extends React.Component{
componentWillMount() {
console.log('ChildComponent will mount');
}
componentDidMount() {
console.log('ChildComponent did mount');
}
render() {
console.count('ChildComponent render');
return <div>
ChildComponent
</div>
}
}
class ParentComponent extends React.Component{
componentWillMount() {
console.log('ParentComponent will mount');
}
componentDidMount() {
console.log('ParentComponent did mount')
ReactDOM.render(
<ChildComponent/>,
document.getElementById('content')
)
}
render() {
console.count('ParentComponent render');
return <div id='parent'>
ParentComponent
<div id='content'></div>
</div>
}
}
ReactDOM.render(
<ParentComponent />,
document.body
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
//normal way:
//ParentComponent will mount
//ParentComponent render: 1
//ChildComponent will mount
//ChildComponent render: 1
//ChildComponent did mount
//ParentComponent did mount
//ReactDOM.render way:
//ParentComponent will mount
//ParentComponent render: 1
//ParentComponent did mount
//ChildComponent will mount
//ChildComponent render: 1
//ChildComponent did mount
看起来很有效!但我发现了两种方式之间的区别。生命周期执行顺序是不同的。但是,还有其他区别吗?我的意思是,可能存在ReactDOM.render
方式会导致麻烦或错误的情况。
我还发现,如果您在浏览器中使用开发工具检查元素,您会在data-reactroot
和ParentComponent
根节点中找到ChildComponent
属性。而正常的渲染方式,它只会在ParentComponent
根节点中消失。