【发布时间】:2018-04-22 20:08:27
【问题描述】:
我有一个 react 类,我需要在其中使用 shouldComponentUpdate(),以防止组件与其父级之间的无限循环。
我只是检查nextProps 的深层克隆是否等于this.props,如果不等于,我只更新组件。
到目前为止,一切都很好。 (?)
class Child extends Component {
onComponentUpdate = (e) => {
this.props.update(e)
}
shouldComponentUpdate(nextProps, nextState) {
return JSON.stringify(nextProps) !== JSON.stringify(this.props)
}
render() {
return (
<div>
// some code that might trigger onComponentUpdate()
</div>
);
}
}
现在,在我的父组件中,发生了一些事情,让我想要重新渲染子组件,而无需更改特定的道具。我现在所做的是更改状态中的计数器并将其作为道具传递给孩子。我从来没有对计数器本身做任何事情,它只是向孩子表明道具实际发生了变化,以便孩子应该更新。
class Parent extends Component {
constructor() {
super()
this.state = { counter: 0 }
}
otherChildChanged = () => {
this.setState({ counter: this.state.counter + 1 })
}
render() {
return (
<div>
<Child
counter={this.state.counter}
update={"some function"}
other={"props"}
>
</Child>
<OtherChild onChange={this.otherChildChanged}>
</OtherChild>
// some code that might trigger onComponentUpdate()
</div>
);
}
}
有没有更好的方法来做到这一点?
【问题讨论】:
-
不知道为什么要重新渲染一个孩子,如果它的道具甚至没有改变?
-
我有一个可调整大小的 div(单击并拖动边框和 div 及其邻居调整大小)。
标签: javascript reactjs components