ste*_*rda 1 javascript reactjs
我很忙。当父母状态改变时,我不希望我的孩子重新渲染。我尝试在子组件中使用 shouldComponentUpdate,但由于某种原因,它甚至没有被调用。
我的问题是这个。我在网格上有几个图表,我想更新其中一个图表配置设置,我将其作为道具传递给组件。他们共享的父级更新了子级的配置,但在此过程中,配置发生了变化,因此它们都重新渲染。
为什么不调用 shouldComponentUpdate ?它在父级上被调用,所以我假设它在状态改变时被调用???
我的代码看起来像:
父级 - 具有 setState Child1 的 selectDataType - 调用作为道具传递的 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;
}
Run Code Online (Sandbox Code Playgroud)
孩子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>
)
}
Run Code Online (Sandbox Code Playgroud)
}
Child2:完全像 Child1
确保您的孩子获得了一个静态键道具(对于所有组件数组)。如果给了他们一个随机密钥,那么当父母重新渲染时,它会给所有孩子一个新的随机密钥(不同于他们的旧密钥)。这将使 React 认为它是一个完全不同的组件,因此现有的组件将完全卸载并重新安装(使用新属性)。所以子组件没有更新,而是重新安装。因此shouldComponentUpdate不会被调用。
| 归档时间: |
|
| 查看次数: |
3167 次 |
| 最近记录: |