【发布时间】:2021-02-14 14:14:49
【问题描述】:
我无法理解为什么在某些情况下 componentWillUnmount 方法不会被调用,即使我期望的组件已卸载。
更具体地说,这是一个例子。让我们考虑一个带有一个按钮和 2 个子组件的父组件:Child_Odd 和 Child_Even。如果按钮的点击次数为奇数则 Child_Odd 为“显示”,否则 Child_Even 为“显示”。
我希望看到当组件“消失”时调用componentWillUnmount 方法,但相反这不会发生。 Here a stackblitz reproducing the case(此 stackblitz 还包括一个类似的情况,其中实际调用了 componentWillUnmount 方法)。
这是相关代码
export class ChildFlipped extends React.Component {
render() {
return (
<div>
{this.props.name} - No of clicks ({this.props.numberOfClicks})
</div>
);
}
}
export class ParentFlips extends React.Component {
constructor(props: any) {
super(props);
this.state = {
clickCounter: 0,
};
}
render() {
return (
<div>
<button
onClick={() => this.updateState()}
>
Click me
</button>
{this.state.clickCounter % 2 ? (
<ChildFlipped
name={"Even"}
numberOfClicks={this.state.clickCounter}
></ChildFlipped>
) : (
<ChildFlipped
name={"Odd"}
numberOfClicks={this.state.clickCounter}
></ChildFlipped>
)}
</div>
);
}
updateState() {
this.setState((prevState, _props) => ({
clickCounter: prevState.clickCounter + 1,
}));
}
}
【问题讨论】:
-
这个答案并没有真正解释什么,它只是展示了如何用钥匙来解决它。