【发布时间】:2018-10-18 23:01:33
【问题描述】:
我在这方面玩得很开心。当父母状态发生变化时,我不希望我的孩子重新渲染。我尝试在子组件中使用 shouldComponentUpdate,但由于某种原因,它甚至没有被调用。
我的问题是这个。我在网格上有几个图表,我想更新其中一个图表配置设置,我将其作为道具传递给组件。他们都共享的父级更新了子级的配置,但在此过程中,配置发生了变化,因此它们都重新渲染。
为什么不调用 shouldComponentUpdate?它在父节点上被调用,所以我假设它是在状态改变的地方调用???
我的代码如下所示:
Parent - 有 selectDataType 和 setState Child1 - 调用作为道具传递的 selectDataType,它重新渲染 Child2 - 没有更改它的道具,但重新渲染,我需要停止
家长:
selectDataType(e) {
e.stopPropagation();
var cellId = e.currentTarget.dataset.id;
var cellValue = e.currentTarget.childNodes[0].value;
var newCells = [];
newCells = this.state.cells.map(function (cell, i) {
var newObj = Object.assign({}, cell);
if (cellId == cell.id) {
newObj['dataType'] = cellValue;
}
return newObj;
});
this.setState({
cells: newCells
});
return;
}
孩子1:
export default class Pie extends React.Component {
constructor(props) {
super(props);
this.create = this.create.bind(this);
}
shouldComponentUpdate() {
return false;
}
create() {
return {
//some data
}
}
render() {
return (
<div>
<ReactECharts
option={ this.create() }
style={{ position: "absolute", top: 0, bottom: 0, left: 0, right: 0, height: "100%" }}
theme="chalk"
notMerge={ true }
/>
</div>
)
}
}
Child2:与 Child1 完全相同
【问题讨论】:
-
shouldComponentUpdate() : Returning false does not prevent child components from re-rendering when their state changes.
-
如何在parent中渲染children?一个可能的原因是没有为子组件提供静态
key属性。例如,如果每次渲染它们时都会给它们一个随机键,那么它们将完全卸载并使用其新的父属性重新安装。所以子组件没有更新,它正在重新安装。因此shouldComponentUpdate不会被调用 -
你能给我们看看父母的渲染吗?
-
ahhhh...@Jayce444 这似乎是合理的。让我检查一下,然后回复你。
-
谢谢@Jayce444。它也解决了我的问题。一直在拉我的头发。
标签: javascript reactjs