[英]How does react js differentiate between component instances?
假設我們有一個文件HomePage.js
:
export default class HomePage extends Component {
constructor(props) {
super(props)
this.index = 0
}
render() {
return (
<p>This is the home page number: {this.index++}</p>
)
}
}
還有一個App.js
:
import React, { Component } from "react";
import { createRoot } from 'react-dom/client';
import HomePage from "./HomePage";
export default class App extends Component {
constructor(props) {
super(props)
this.index = 0
}
render() {
if (this.index++ < 10)
return (
<div>
<HomePage />
</div>
)
return (
<div>
<HomePage />
<HomePage />
</div>
)
}
}
function homePageTick () {
const element = (
<App />
)
root.render(element)
}
const appDiv = document.getElementById("app")
const root = createRoot(appDiv)
setInterval(homePageTick, 1000)
請原諒我的代碼很長,但有必要解釋我的問題。
總結一下代碼的實際作用:我相信,首先,它創建了一個HomePage
實例,其計數器從零開始並向上計數。 10 秒后,它創建另一個HomePage
實例,其計數器從零開始並向上計數。
這讓我大吃一驚,我認為每一秒都會創建一個新的HomePage
實例,因此計數器只會顯示為零? react如何知道哪個實例是哪個? 它怎么知道直到 10 秒后才需要創建新實例,我如何創建一個新實例來替換第一個實例? 重新啟動計數器?
首先,這種模式非常奇怪:
function homePageTick () {
root.render(<App/>)
}
setInterval(homePageTick, 1000)
您應該只調用一次root.render
,然后使用 effects 和 state 來更改應用程序的內容。
現在你的問題是,當 React 重新渲染並在同一個地方看到同一個組件時,它會重用現有的實例。 當 React 比較兩棵樹<div><HomePage/></div>
和<div><HomePage/></div>
時,它發現它們是相同的(因為HomePage === HomePage
),因此重用了現有的HomePage
實例(為了不丟失內部狀態)。 10 秒后,當比較<div><HomePage/></div>
和<div><HomePage/><HomePage/></div>
時,它將為第一個重用現有的HomePage
組件,並創建一個新的一個用於第二個以前不存在的。
如果你想強制 React 創建同一個組件的新實例,你可以給它們不同的key
屬性。 例如<HomePage key={this.index}/>
。
您可以閱讀https://reactjs.org/docs/reconciliation.html了解更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.