【问题标题】:Countdown time to trigger parent comment state change触发父评论状态变化的倒计时时间
【发布时间】:2019-05-04 04:31:25
【问题描述】:

我有一个倒数计时器作为子元素。一旦时钟达到 0,我将通知父组件更新状态以呈现其他内容。我在控制台中收到此错误,我不确定如何修复。它似乎也陷入了一个循环。我错过了什么?

错误 - 警告:在现有状态转换期间无法更新(例如在render 内)。渲染方法应该是 props 和 state 的纯函数。

路径:Clock.jsx (parent)

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timeComplete: false
    };
    this.myCallback = this.myCallback.bind(this);
  }

  myCallback = () => {
    this.setState({ timeComplete: true });
  };

  render() {
    let now = new Date();
    now.setSeconds(now.getSeconds() + 2); // timestamp
    now = new Date(now);

    return (
      <div className="container-fluid bg-light h-100">
        <CountdownTimer timerSeconds={now} callbackFromParent={this.myCallback} />
      </div>
    );
  }
}

export default Clock;

路径:CountdownTimer.jsx (child)

class CountdownTimer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    const { timerSeconds } = this.props;

    const renderer = ({ minutes, seconds, completed }) => {
      if (completed) {
        // Render a completed state
        this.props.callbackFromParent('listInfo');
      }
      return (
        <span>
          {minutes} min {seconds} sec
        </span>
      );
    };
    return <Countdown date={timerSeconds} renderer={renderer} />;
  }
}

export default CountdownTimer;

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    所以这是我的一个愚蠢的错误,但我相信其他人会犯的。当您尝试更新父组件中的状态时,您需要从子组件调用该函数。在这种情况下:

    this.props.callbackFromParent('listInfo');

    应该是

    this.props.myCallback;

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      相关资源
      最近更新 更多