![](/img/trans.png)
[英]How can you initialize a child components state from inside a parent component in react?
[英]How can saving React Child Components inside state value be efficient?
我正在做一些需要動態添加反應子組件的項目。 雖然這項任務似乎很容易完成,但我擔心我的方法的效率。 我在網上沖浪,發現了幾個與我的設計模式相同的解決方案。 不過,我懷疑自己的效率。
下面是我的例子:
class Container extends Component{
constructor(props){
super(props)
this.state = {
children: []
}
this.addChild = this.addChild.bind(this)
}
addChild(){
this.setState({
children: [...this.state.children,
<div>
<h1> My number is {this.state.children.length} </h1>
</div>]
})
}
render() {
return
<div>
<button onClick={this.addChild}> Add child </button>
{this.state.children.map( child => child)}
</div>
}
}
這個例子非常簡單。 但是當你有一個復雜的結構,其中組件有其他改變狀態的組件,有事件偵聽器和深層結構,組件的狀態值將包含大量代碼,這個組件將在每次添加時重新渲染所有內容。 在第 100 次添加時,它將進行99 次不必要的重新渲染。
當然,我可以使用Vanilla JS或JQuery來附加新組件,但我認為這不是明智的決定。 我想保持一致性並使用 React 工具解決問題。
你怎么看? 你會建議什么模式?
好的,我自己已經找到了這個問題的答案。 盡管React在每次狀態 更改時都調用render 函數 ,但它不會重新渲染不必要的組件。
3 年后,我發現這種方法很糟糕。 應該將狀態值存儲在數組中並在渲染函數中迭代它們。 不僅代碼看起來更清晰,而且內存使用量也會減少。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.