【问题标题】:componentWillUnmount method not called when react Component disapearsreact Component消失时未调用componentWillUnmount方法
【发布时间】: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,
    }));
  }
}

【问题讨论】:

标签: reactjs react-lifecycle


【解决方案1】:

它不会触发,因为组件仍然挂载。关于和解,条件表达式

this.state.clickCounter % 2
? <ChildFlipped name={"Even"} numberOfClicks={this.state.clickCounter}/>
: <ChildFlipped name={"Odd"} numberOfClicks={this.state.clickCounter}/>

没有区别
<ChildFlipped name={this.state.clickCounter % 2? "Even" : "Odd"} 
              numberOfClicks={this.state.clickCounter}/>

因为这两个子句都引用同一个ChildFlipped 组件。如果添加键,则可以使它们可区分并触发卸载:

his.state.clickCounter % 2
? <ChildFlipped key='even' name={"Even"} numberOfClicks={this.state.clickCounter}/>
: <ChildFlipped key='odd' name={"Odd"} numberOfClicks={this.state.clickCounter}/>

为了试验生命周期方法,我构建了一个 React lifecycle visualizer (StackBlitz),它可能对你有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    相关资源
    最近更新 更多