我正在使用带有以下组件的React实现一个非常简单的图表页面: 设计器:具有列。 列:如果具有工具,则呈现图表。 图表:将绘制一个Highchart图表。
问题是当我更改任何列的状态时的性能,因此我在Designer中调用this.setState({columns: columnsArr})
时,React将渲染所有列,例如,如果我们有60列,则将花费很长时间。
我读过,React仅在其prop更改时才渲染该组件,因此对于column组件,如果更改一列,则它不应渲染所有列。那我在这里想念什么?
这是我的代码:
`
class Chart extends Component {
constructor(props) {
super(props);
this.handleDelete = this.handleDelete.bind(this);
}
handleDelete() {
this.props.removeTool(this.props.index);
};
render() {
return (
<div id={"Chart_"+this.props.index}>
<div>
<button onClick={(e)=>{this.handleDelete()}} className="btn btn-sm btn-danger"><i className="fa fa-trash btn-danger"></i></button>
</div>
<div>
<HighchartsReact key={"H_" + this.props.index} highcharts={Highcharts} options={options} update={false} />
</div>
</div>
);
}
};
class Designer extends Component {
constructor(props, context) {
super(props, context);
this.state = {
columns: [
{ name: 'c1', hasTool: true },
{ name: 'c2', hasTool: true },
{ name: 'c3', hasTool: true },
{ name: 'c4', hasTool: true },
{ name: 'c5', hasTool: true }
]
}
this.toogleHasTool = this.toogleHasTool.bind(this);
}
toogleHasTool(columnId) {
var columnsArr = this.state.columns;
columnsArr.find(function (c) { return c.name === columnId }).hasTool = !columnsArr.find(function (c) { return c.name === columnId }).hasTool;;
this.setState({ columns: columnsArr })
}
render() {
var fn = this.toogleHasTool;
return (
<div id="container">
{
this.state.columns.map(function (column, i) {
return <Column key={"Col_"+column.name} index={column.name} hasTool={column.hasTool} toogleHasTool={fn} />
})
}
</div>
);
}
};
class Column extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="col-sm-3" >
{this.props.hasTool ? (<Chart key={"C_" + this.props.index} index={this.props.index} removeTool={this.props.toogleHasTool}> </Chart>) : ("")}
</div>
);
}
};`
答案 0 :(得分:0)
您可以尝试在Column类中扩展PureComponent
。这些组件仅在其状态或道具已更改的情况下才会重新渲染。请注意,它对这些对象进行了浅(而非深)比较。因此,如果只有一个Column发生更改,则不会调用其他的 render()方法。