我有一个名为“ App”的父组件,其中使用了一个子组件 'NewComp'。我已经在子组件中定义了componentDidUpdate()生命周期,而不是 在父组件中。
父组件:
class App extends Component {
state = {
count:0,
}
change = () =>{
this.setState({
count:this.state.count+1,
})
}
render() {
return (
<div>
<p>Count = {this.state.count}</p>
<button onClick={this.change}>Add Count</button>
<NewComp />
</div>
);
}
}
子组件:
export default class NewComp extends Component {
componentDidUpdate(){
console.log('Child component did update');
}
render() {
return (
<div>
<h1>Child Component</h1>
</div>
)
}
}
现在,每次我通过“添加计数”按钮更改父状态时,即使子组件中没有任何更改,子组件中的componentDidMount()也会执行
答案 0 :(得分:1)
父组件被触发重新渲染,并且在您的NewComp
中,shouldComponentUpdate
默认情况下始终返回true,因此NewComp
也被触发重新渲染。您可以通过在shouldComponentUpdate
中实现NewComp
或使用PureComponent
来避免这种情况:
export default class NewComp extends PureComponent {
componentDidUpdate(){
console.log('Child component did update');
}
render() {
return (
<div>
<h1>Child Component</h1>
</div>
)
}
}
答案 1 :(得分:0)
您可以使用shouldComponentUpdate
生命周期方法来控制组件何时可以更新。通常componentDidUpdate
是在道具或状态更新时执行的。
答案 2 :(得分:0)
您可以看到以下查询。类似于您的
React: Parent component re-renders all children, even those that haven't changed on state change
我希望它会有所帮助。
答案 3 :(得分:0)