首页 > 解决方案 > reactjs中的条件componentWillUnmount()

问题描述

单击时buttonquote应该使用卸载,componentwillunmount()但我通过登录到控制台进行了检查,卸载根本没有运行。

import React from "react";

import "./App.css";

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      quote: ""
    };
  }

  handleAction = () => {
    this._isRemoved = true;

    console.log("Clicked");
  };

  componentDidMount() {
    this._isRemoved = false;

    if (!this._isRemoved) {
      this.setState({ quote: "Something" });

      console.log("Mounted");
    }
  }

  componentWillUnmount() {
    this._isRemoved = true;

    console.log("Unmount");
  }

  render() {
    return (
      <div className="App">
        <div>
          <q>{this.state.quote}</q>
          <br />

          <button onClick={this.handleAction}>Click Here</button>
        </div>
      </div>
    );
  }
}

export default App;

标签: reactjsreact-lifecyclereact-component-unmount

解决方案


当您更改页面或整个组件将消失的东西时调用它的卸载。

你可以像这个例子一样简单地隐藏或显示你的元素:

import React from "react";

import "./App.css";

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      quote: "",
      _isRemoved :false
    };
  }

  handleAction = () => {
    this.setState({
      _isRemoved : true
    })
    console.log("Clicked");
  };

  showAction = () => {
    this.setState({
      _isRemoved : false
    })
    console.log("Clicked");
  };

  componentDidMount() {

    this.setState({ quote: "Something" });

    console.log("Mounted");
    
  }

  componentWillUnmount() {
    this._isRemoved = true;

    console.log("Unmount");
  }

  render() {
    return (
      <div className="App">
        <div>
          {!this.state._isRemoved &&
            <q>{this.state.quote}</q>
          }
          <br />

          <button onClick={this.handleAction}>Hide</button>
          <button onClick={this.showAction}>Show</button>
        </div>
      </div>
    );
  }
}

export default App;

推荐阅读