reactjs - 在ReactJS中setState之后似乎没有调用componentDidMount

标签 reactjs

学习 ReactJS 我正在开发一个简单的倒计时应用程序。倒计时组件如下所示:

const Countdown = React.createClass({
  getInitialState: function() {
    return {
      remaining: 10,
      running: true,
    };
  },
  componentDidMount: function(){
    if (this.state.running) {
      setInterval(this.tick, 1000);
    } else {
      console.log("already paused");
    };
  },
  tick: function(){
    if (this.state.remaining === 0) {
      this.setState({ remaining: 10 });
      this.props.updateStats();
    } else {
        this.setState({ remaining: this.state.remaining -1 });
    };

  },
  handlePauseClick: function(){
    this.setState({ running: false });
  },
  render: function(){
    const s = this.state.remaining;
    return (
      <div className='ui centered card'>
        <div className='content centered'>
          <h1>{helpers.secondsToHuman(s)}</h1>
          <ButtonControls
            handlePauseClick={this.handlePauseClick}
          />
        </div>
      </div>
    )
  },
});

倒计时开始。当点击暂停按钮时,它应该停止。 componentDidMount 仅在 running 为 true 时运行计时器:

if (this.state.running) {
  setInterval(this.tick, 1000);
} else {
  console.log("already paused");
};

处理点击后:

this.setState({ running: false });

我预计组件会重新渲染并且 componentDidMount 将再次执行。但这并没有发生。 componentDidMount 似乎只运行一次。

感谢您的想法

最佳答案

componentDidMount仅在 React 组件安装到树时执行一次,这就是为什么在 setState 之后不会调用它。

所以你需要componentDidUpdate ,除了第一次重新渲染外,每次重新渲染都会执行此回调。对于第一个,您可能需要使用 componentDidMount

此外,您没有清除 else block 中的间隔,这意味着即使组件再次重​​新渲染,tick 函数也不会停止执行。

<小时/>

试试这个

componentDidMount: function() {
   this.tickInterval = setInterval(this.tick, 1000);
},

componentDidUpdate: function() {
  // if app is running and there is no tickInterval yet, set it
  if (this.state.running && this.tickInterval === null) {
    this.tickInterval = setInterval(this.tick, 1000);
  // if app is stopped, but there is a tickInterval, clear it
  } else if (!this.state.running && this.tickInterval !== null) {
    clearInterval(this.tickInterval);
    this.tickInterval = null;
  }
},

componentWillUnmount() { 
  clearInterval(this.tickInterval);
}

关于reactjs - 在ReactJS中setState之后似乎没有调用componentDidMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41102738/

相关文章:

javascript - 如何使用 .map 迭代对象?

javascript - 如何在Reactjs中启用CORS?

javascript - React router v4 无法构建

javascript - 如何连接 JSX 而不会遇到 "single root"问题与 JSX

javascript - 具有不可变状态的循环内的对象更新

javascript - 对于这个 angularjs 代码,reactjs 中的等效代码是什么

javascript - 我有一个虚假数据对象,我想复制它,我该怎么做?

reactjs - 为什么组件被重新渲染两次?

javascript - ReactJS 异步,等待结果

node.js - 测试 then() block 内的代码