2017-08-07 186 views
0

我對下面的代碼有一些疑問。react - 如何實例化組件以及它們何時相同?

據我所知,Example是一個類,它在ReactDOM.render作爲參數傳遞時首先被實例化。

當它被渲染時,它首先調用componentWillMount方法。

我不明白的是第二個ReactDOM.render調用。

<Example />在第二個ReactDom.render調用與第一個相同。

我認爲第二個調用實例化了第二個實例,但顯然它並不是因爲componentWillMount方法沒有被調用。

爲什麼兩個<Example />是同一個實例?我如何創建第二個/單獨的<Example />實例?

import React from 'react'; 
import ReactDOM from 'react-dom'; 

export class Example extends React.Component { 
    componentWillMount() { 
    alert('component is about to mount!'); 
    } 

    render() { 
    return <h1>Hello world</h1>; 
    } 
} 

ReactDOM.render(
    <Example />, 
    document.getElementById('app') 
); 

setTimeout(() => { 
    ReactDOM.render(
    <Example />, 
    document.getElementById('app') 
); 
}, 2000); 
+2

通常情況下,你只能叫ReactDOM.render有一次,這可能是一個例子,表明您可以多次調用ReactDOM.render來覆蓋現有的已裝載組件 – Axnyff

+1

此外,作爲[documentation](https://facebook.github.io/react/docs/react-dom的.html)陳述如下:_如果React元素先前已被渲染到容器中,則會對其執行更新,並且僅根據需要變更DOM以反映最新的React元素._ –

回答

0

如果你想兩個實例,那麼你應該有兩個主要的div不同ID:

import React from 'react'; 
import ReactDOM from 'react-dom'; 

export class Example extends React.Component { 
    componentWillMount() { 
    alert('component is about to mount!'); 
    } 

    render() { 
    return <h1>Hello world</h1>; 
    } 
} 

ReactDOM.render(
    <Example />, 
    document.getElementById('app') 
); 

ReactDOM.render(
    <Example />, 
    document.getElementById('appTwo') 
); 

而在HTML:

<div id="app"></div> 
<div id="appTwo"></div> 
相關問題