代码之家  ›  专栏  ›  技术社区  ›  shubham saurabh

如何在reactjs中的setInterval内返回JSX

  •  0
  • shubham saurabh  · 技术社区  · 7 年前

    我需要重新运行JSX,但我不知道如何执行此bcz setInterval不返回JSX。我是否可以选择其他方式或修改相同的代码:

    renderCountdown = (start) => {
        let appointmentDuration = new Date(this.state.appointmentEndDate).getTime() - new Date(this.state.appointmentStartDate).getTime();
        let countDownDate = new Date(this.state.appointmentStartDate).getTime();
        let countDownTime = countDownDate;
        let x = setInterval(() => {
            let now = new Date().getTime();
            let distance = countDownDate - now;
            // console.log('distance--------', distance);
            let days = Math.floor(distance / (1000 * 60 * 60 * 24));
            // console.log('days------', days);
            let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            let seconds = Math.floor((distance % (1000 * 60)) / 1000);
            let countdown = days + 'd ' + hours + 'h ' + minutes + 'm ' + seconds + 's ';
            if (distance === 0) {
                return (
                    <button className="message button clickable" onClick={start}>Click to Start Call </button>
                );
            } else if (distance > 0) {
                return (
                    <p> <b>Appointment starts in :</b> <span>{countdown}</span></p>
                );
            } else if (distance < 0) {
                return (
                    <h2>Appointment Expired</h2>
                );
                clearInterval(x);
            };
        }, 1000);
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Giang Le    7 年前

    我无法帮助您如何在setInterval中返回jsx,但有一种简单的方法可以解决您的问题。您将拥有一个名为 distance 。每秒钟都会减少这种状态。在“渲染”中,检查“距离”的值并渲染所需的内容。下面是示例代码

    constructor(props) {
      //calc countDownDate
      //now can access props 
      this.state = {
        distance: countDownDate - now;
      }
    }
    
    componentDidMount() {
      this.countDown = setInterval(() => {
        const {distance} = this.state
        //Calc the new distance
        if(distance < 0) {
          clearInterval(this.countDown)
        }
        this.setState({distance: newDistance})
      }, 1000)
    }
    
    
    componentWillUnount() {
      clearInterval(this.countDown)
    }
    
    
    render() {
      const {distance} = this.state
      if (distance === 0) {
            return (
                <button className="message button clickable" onClick={start}>Click to Start Call </button>
            );
        } else if (distance > 0) {
            return (
                <p> <b>Appointment starts in :</b> <span>{countdown}</span></p>
            );
        } else if (distance < 0) {
            return (
                <h2>Appointment Expired</h2>
            );
        };
    }