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);
通常情況下,你只能叫ReactDOM.render有一次,這可能是一個例子,表明您可以多次調用ReactDOM.render來覆蓋現有的已裝載組件 – Axnyff
此外,作爲[documentation](https://facebook.github.io/react/docs/react-dom的.html)陳述如下:_如果React元素先前已被渲染到容器中,則會對其執行更新,並且僅根據需要變更DOM以反映最新的React元素._ –