Javascript 为什么删除一个组件会影响另一个组件的生命周期?

Javascript 为什么删除一个组件会影响另一个组件的生命周期?,javascript,reactjs,Javascript,Reactjs,下面的代码示例包含两个组件:Component1logsprevState使用componentdiddupdate方法,单击按钮即可删除Component2,显示使用componentWillUnmount const{useState}=React; 类Component1扩展了React.Component{ 建造师(道具){ 超级(道具); 此.state={ 姓名:'约翰', }; } componentDidUpdate(prevProps、prevState){ console.

下面的代码示例包含两个组件:
Component1
logs
prevState
使用
componentdiddupdate
方法,单击按钮即可删除
Component2
,显示使用
componentWillUnmount

const{useState}=React;
类Component1扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
姓名:'约翰',
};
}
componentDidUpdate(prevProps、prevState){
console.log(prevState);
}
render(){
返回(
名称为{this.state.name}
在此处键入以在控制台中查看prevState:
{
this.setState({name:e.target.value});
}}
/>
);
}
}
类Component2扩展了React.Component{
componentDidMount(){
console.log('Mount');
}
组件将卸载(){
console.log('Unmount');
}
render(){
返回(
单击按钮以删除该图元
);
}
}
常量应用=()=>{
const[showComponent,setShowComponent]=useState(true);
返回(
{showComponent?:null}
{
设置显示组件(假);
}}
>
去除
);
};
//渲染它
render(,document.getElementById('react')


当应用程序被渲染时,其子应用程序也会被渲染。您可以尝试使Component1成为一个
反应。如果您想减少重新渲染,可以使用PureComponent
或定义
shouldComponentUpdate

当您使用按钮中的
设置ShowComponent
更改状态时,您实际上是在渲染
-因此,它内部的组件应该触发卸载、装载、,更新等等。。这里说初始渲染没有调用
componentDidUpdate
?是的,。添加到@choz的注释中,您可以使用React-memo或pure-components来避免不必要地重新呈现子组件,因为如果父组件的任何状态发生更改,子组件将再次被调用,因为只有状态更新才能告知React-to-re-render。您的意思是单击该按钮会触发重新呈现
应用程序
组件吗?我不同意,因为在组件初始呈现时未调用
componentdiddupdate
。@thinkvantagedu
componentdiddupdate()
在更新发生后立即调用。初始渲染时不调用此方法。重新呈现
App
是否等于更新组件1的状态?@thinkvantagedu是的,确实如此。因此,要重新渲染时请仔细选择。子组件和子组件的子组件都被重新呈现。@thinkvantagedu您只需将Component1的继承从component更改为PureComponent即可<代码>类组件1扩展了React.PureComponent{…}