【发布时间】:2018-11-21 15:41:04
【问题描述】:
我正在做一些需要动态添加反应子组件的项目。虽然这项任务似乎很容易完成,但我担心我的方法的效率。我在网上冲浪,发现了几个与我的设计模式相同的解决方案。尽管如此,我还是怀疑自己的效率。
下面是我的例子:
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 工具解决问题。
你的想法是什么?你会建议什么模式?
【问题讨论】:
-
您可以查看
PureComponent概念并尝试围绕它组织您的代码。这是一个工作示例:stackoverflow.com/a/50463828/4312466 -
@JordanEnev 谢谢!
标签: javascript reactjs design-patterns ecmascript-6