反应:setState 与倒计时

React: setState with Countdown

我的主 App.js class 中有一个状态计数器。我还有一个 Countdown.js,它会在他每次完成时更新他的 parent class 的计数器。但是当计时器完成一次时,我得到一个错误。此外,状态计数器从 0 跳到 2 而不是从 0 跳到 1...

Warning: Cannot update during an existing state transition (such as within `render`).

我怎样才能摆脱这个错误?或者您有解决方案如何在计时器结束时计算 ++ 吗?

我的 class App.js:

import React from "react"
import "./App.css"
import Countdown from "./Countdown.js"

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      counter: 0
    };
    this.count = this.count.bind(this);
  }

  count() {
    this.setState(prevState => ({
      count: prevState.counter++
    }));
  }

  render() {
    return (
      <div className="window">
        <p>{this.state.counter}</p>
        <Countdown count={this.count} />
      </div>
    );
  }
}

export default App

我的Countdown.js

import React from "react";
import CountDown from "react-countdown";

class CountdownQuestion extends React.Component {
  constructor() {
    super();
    this.state = {
      time: 3000
    };
  }

  render() {
    const renderer = ({ seconds, completed }) => {
      if (completed) {
        this.props.count();
        return <h2>Zeit abgelaufen</h2>;
      } else {
        return <h3>{seconds}</h3>;
      }
    };

    return (
      <CountDown date={Date.now() + this.state.time} renderer={renderer} />
    );
  }
}

export default CountdownQuestion;

嗯,和错误说的一模一样。您不能在渲染期间更新状态(如在 count() 函数中)。您可能最好使用 onComplete 挂钩。

class CountdownQuestion extends React.Component {
  constructor() {
    super();
    this.state = {
      time: 3000
    };
  }

  render() {
    // Removing this.props.count() from this function also keeps it more clean and focussed on the rendering.
    const renderer = ({ seconds, completed }) => {
      if (completed) {
        return <h2>Zeit abgelaufen</h2>;
      } else {
        return <h3>{seconds}</h3>;
      }
    };

    return (
      <CountDown
        date={Date.now() + this.state.time}
        onComplete={this.props.count} // <-- This will trigger the count function when the countdown completes.
        renderer={renderer}
      />
    );
  }
}