在父组件`componentDidMount`生命周期中调用ReactDOM.render

时间:2016-08-30 02:21:09

标签: javascript facebook reactjs web react-native

我对此很好奇。我在下面写了一个演示:

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-reactrootParentComponent根节点中找到ChildComponent属性。而正常的渲染方式,它只会在ParentComponent根节点中消失。

0 个答案:

没有答案