首页 > 解决方案 > 模态倒计时

问题描述

import React, { Component } from 'react';
import { Button, Header, Icon, Modal } from 'semantic-ui-react';
import { setInterval } from 'timers';

export default class LogoutModal extends Component {
  state = { timer};
  componentDidMount() {
    setInterval(() => this.today(), 1000);
  }

  today() {
    this.setState({
      timer:this.state.timer - 1
    });
  }

  render() {
    return (
      <Modal
        open={this.props.handleOpen}
        onClose={this.props.handleClose}
        basic
        size="small"
      >
        <Header icon="browser" content="Cookies policy" />
        <Modal.Content>Time left is: {this.state.timer}</Modal.Content>
        <Modal.Actions>
          <Button color="green" onClick={this.props.handleClose} inverted>
            <Icon name="checkmark" /> Got it
          </Button>
        </Modal.Actions>
      </Modal>
    );
  }
}

我正在尝试在语义 ui 模式上显示倒计时,但它只显示计时器初始值 5。请问可能有什么问题我试图在语义 ui 模式上显示倒计时,但它只显示计时器初始值 5 . 请问有什么问题

标签: reactjssemantic-ui

解决方案


我不确定“计时器”是什么包,但是,如果这不起作用,我建议将您的时间间隔放入 CDM 中自己的变量中,您应该尝试使用普通的 setInterval。类似这样的东西:

this.timer = setInterval(() => {
  this.setState({
    timer:this.state.timer - 1
  });
}, 1000);

另外,不要忘记在 handleClose 和 componentWillUnmount 中清除您的时间间隔。

clearInterval(this.timer);

推荐阅读