javascript - 如何让这个按钮来重置这个 react 组件中的计时器?

标签 javascript reactjs es6-class

我有以下 ES6 的基本 ReactJS 设置。当我按下重置按钮时,计时器不会回到“0”。我究竟做错了什么?我对 React 还很陌生,所以任何代码组织和其他技巧也很感激。

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      seconds: 0
    }
    this.resetTimer.bind(this)
  }
  resetTimer = () => {
    this.setState({seconds: 0})
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
        <Button label="Start"/>
        <Button label="Stop"/>
        <Button label="Reset" onClick={this.resetTimer} />
        <Timer seconds={this.state.seconds} />
      </div>
    );
  }
}

class Button extends Component {
  render() {
    return(
      <div>
        <button onClick={this.props.onClick} >{this.props.label}</button>
      </div>
    );
  }
}

class Timer extends Component {
  constructor(props) {
    super(props)
    this.state = {
      seconds: this.props.seconds
    };
  }
  componentDidMount() {
    this.timerId = setInterval(
      () => this.tick(),
      1000
    );
  }
  tick() {
    this.setState({ seconds: this.state.seconds + 1});
  }
  componentWillUnmount() {
    clearInterval(this.timerId);
  }
  render() {
    return (
      <div>{secToMin(this.state.seconds)}</div>
    );
  }
}

export default App;

最佳答案

问题出在您的代码中,您仅将 seconds 属性值分配给构造函数中的 state 。构造函数仅被调用一次,之后,对 seconds 属性的更改不会更新 Timer 组件的状态。

所以当 props 改变时你需要手动更新状态。您可以使用componentWillReceiveProps()生命周期方法执行此操作如下。

componentWillReceiveProps(nextProps){
  this.state = {
    seconds: nextProps.seconds
  };
}

此外,您实际上不需要将 this 绑定(bind)到 resetTimer,因为 resetTimerarrow function 。因此,您可以安全地从构造函数中删除 this.resetTimer.bind(this) 行。

关于javascript - 如何让这个按钮来重置这个 react 组件中的计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44013777/

相关文章:

javascript - 如何在graphql gatsby中允许可选的清晰图像?

reactjs - 如果 props 相等,为什么组件会重新渲染

javascript - 有没有更好的方法在 React Component 类中绑定(bind) 'this'?

javascript - 试图弄清楚范围是如何工作的

javascript - 无法在 Karaf OSGi 中加载 ScriptEngineManager 和 ScriptEngine(找不到 Nashorn)

javascript - 无法点击 iOS 模拟器中的文本字段或按钮

javascript - 我如何以及为什么要编写一个扩展 null 的类?

javascript - angular2 http拦截器和注入(inject)SlimLoadingBarService不起作用?

javascript - Ember.Instrumentation API 示例

wordpress - 将 Container Div 添加到 WordPress 中的每个 Gutenberg-Block