正确卸载反应组件

时间:2017-10-12 23:47:14

标签: javascript reactjs ecmascript-6

抱歉,我无法为这个问题提出更具体的标题。当我执行下面的代码片段时,我收到以下警告:

  

警告:setState(...):只能更新已安装或安装的组件。这通常意味着您在已卸载的组件上调用了setState()。这是一个无操作。请检查打字机组件的代码。

但是,如果MyComponent中的render()更改为以下内容,则不会出现此类警告:

render() {
  return (
    <div>
      <h1>
        <Typewriter />
        { this.state.render == 1 && "Render 1" }
        { this.state.render == 2 && "Render 2" }
        { this.state.render == 3 && "Render 3" }
      </h1>
    </div>
  );
}

如何正确卸载此呈现的Typewriter组件,该组件本身正在执行某些安装和卸载操作?谢谢!

&#13;
&#13;
class Typewriter extends React.Component {
  constructor(props) {
    super();
    this.state = {
      finalText: ''
    }
    this.typeWriter = this.typeWriter.bind(this);
  }

  typeWriter(text, n) {
    if (n < (text.length)) {
      if (n + 1 == (text.length)) {
        let j = text.substring(0, n+1);
        this.setState({ finalText: j });
        n++;
      }
      else {
        let k = text.substring(0, n+1) + '|';
        this.setState({ finalText: k });
        n++;
      }
      setTimeout( () => { this.typeWriter(text, n) }, 100 );
    }
  }

  componentDidMount() {
    this.typeWriter('testing_typewriter', 0);
  }

  render() {
    return (
      <div>
        { this.state.finalText }
      </div>
    );
  }
}

class MyComponent extends React.Component {
  constructor(props) {
    super();
    this.state = {
      render: 1,
      update: false
    };
    this.interval = null;
  }

  componentDidMount() {
    this.interval = setTimeout( () =>
      this.rendering(), 1700
    );
  }

  componentWillUpdate(nextProps, nextState) {
    if (this.state.render < 3) {
      this.interval = setTimeout( () =>
        this.rendering(), 1200
      );
    }
  }

  componentWillUnmount() {
      clearInterval(this.interval);
      this.interval = null;
  }

  rendering() {
    if (this.state.render < 3) {
      if (this.interval) {
        this.setState({ render: this.state.render + 1 });
      }
    }
  }

  render() {
    return (
      <div>
        <h1>
          { this.state.render == 1 && "Render 1" }
          { this.state.render == 2 && <Typewriter /> }
          { this.state.render == 3 && "Render 3" }
        </h1>
      </div>
    );
  }
}



ReactDOM.render(<MyComponent />, app);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="app"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

我有一个类似的问题,我通过清除componentWillUnmount函数中的超时/间隔来解决它

在打字机功能中,您需要跟踪此超时:

setTimeout( () => { this.typeWriter(text, n) }, 100 );

类似

this._timer = setTimeout( () => { this.typeWriter(text, n) }, 100 );

然后添加生命周期方法:

componentWillUnmount() {
  window.clearTimeout(this._timer);
}