I am just curious about this. I write a demo below:
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="http://ift.tt/290WjWg"></script>
<script src="http://ift.tt/28SLhWn"></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
It seems works! But I found the difference between the two ways. The lifecycle execute order is different. But, is there any other difference? I mean, maybe there is a case that the ReactDOM.render
way will cause a trouble or error.
I also found that if you inspect the element in browser use develop tools, you will find that the data-reactroot
property both in ParentComponent
and ChildComponent
root node. And the normal render way, it just disappear in ParentComponent
root node.
Aucun commentaire:
Enregistrer un commentaire