我想在reactjs中以每秒的间隔将当前计时值呈现给HTML

时间:2017-11-06 05:38:36

标签: reactjs jsx

我想使用reactjs以每秒的间隔将当前计时值呈现给HTML。我粘贴下面的代码。我在代码下运行时遇到错误。

import react from "react";

**Defined class**
export default class IndependentTimer extends react.Component {
    constructor() {
        super();
        this.state = {
            value: ""
        };

        this.customFunction = this.customFunction.bind(this);
    }

**This function is responsible for generating current time.**   
    customFunction() {
        console.log("customFunDis display!");
        return (<h1> Time is : {new Date().toLocaleTimeString()} </h1>);
    }

**render function**
    render() {
        return (
            <div>
                {**What to do here?**}
            </div>
        );
    }
}

** Error I Got is : **
I got that error at every interval of time.

VM413:1 Uncaught SyntaxError: Unexpected identifier
setInterval (async)     
render  @   index.js:31245

3 个答案:

答案 0 :(得分:2)

setInterval()方法中放置render()会在每次更新组件时创建一个全新的setInterval()

最佳做法是在组件的setInterval()生命周期方法中创建一个componentDidMount()方法,如下所示:

componentDidMount() {
  this.timer = setInterval(this.tick, 1000)
}

每当您希望拆卸组件时,您还必须清除setInterval()

componentWillUnmount() {
  clearInterval(this.timer)
}

你应该得到类似下面代码的东西。

// React.
import React from 'react'

// Independent Timer.
export default class IndependentTimer extends React.Component {

  // Constructor.
  constructor(props) {

    // Super Props.
    super(props)

    // State.
    this.state = {
      time: new Date()
    }
  }

  // Render.
  render() {
    const time = this.state.time
    return `${time * 1}`
  }

  // Did Mount.
  componentDidMount() {
    this.timer = setInterval(this.tick, 1000)
  }

  // Tick.
  tick = () => {
    console.log('Tick.')
    return this.setState({time: new Date()})
  }

  // Will Unmount.
  componentWillUnmount() {
    clearInterval(this.timer)
  }
}

您可能还想查看有关创建时钟组件的官方React文档中的this tutorial

答案 1 :(得分:0)

import React, { Component } from 'react';
class App extends Component {
  constructor() {
    super();
    this.state = {time:new Date()};
    this.startTimer = this.startTimer.bind(this);
    this.sTimer = this.sTimer.bind(this);
  }

  startTimer() {
   setInterval(this.sTimer, 1000)
  }
  sTimer() {
   this.setState({
   time:new Date()
   });
  }
  render() {
   return(
    <div>
      <button onClick={this.startTimer}>Start</button>
      {this.state.time.toLocaleTimeString()}
    </div>
  );
}

}export default App;

使用这个课程可能对你有帮助..

答案 2 :(得分:-1)

你需要牢记的几件事情

首先:你在创建你的React组件时有一个错字。它应该扩展React.Component,您需要导入react大写为import React from 'react',因为它在内部使用React.createElement,否则会失败。

其次:setInterval将第一个参数作为函数而不是返回的HTML。当你写

setInterval(this.customFunction(),1000)

您每1秒执行customFunction并返回一个不正确的HTML。 setInterval也返回一个整数,它是计时器的唯一ID,所以

   <div>
                {
                    setInterval(this.customFunction(),1000)
                }
            </div>

不会工作。您应该在componentDidMount函数中有一个setInterval,然后使用setState将计时器值存储在状态中,该状态会重新呈现您的组件,以便反映您的更改

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

                this.customFunction = this.customFunction.bind(this);
            }

            componentDidMount() {
                console.log("timer display!");
                this.timer = setInterval(this.customFunction,1000)
            }

            componentWillUnmount() {
                clearInterval(this.timer);
            }
            //Custom function which calculates current time.

 customFunction() {
        console.log("customFunDis display!");
        this.setState({time: new Date().toLocaleTimeString()});
 
 }

render() { 
            return (
                <div>
                 <h1> Time is : {this.state.time} </h1>
                </div>
            );
        }

    }
    
ReactDOM.render(<IndependentTimer/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>