javascript – 如何在反应中使用setInterval?

我希望以下应用程序在屏幕上每秒打印一次DAnce.

import React from 'react';
import ReactDOM from 'react-dom';

export class Sample extends React.Component {
    sample(text, i) {
        return <h1> DAnce</h1>;
    }

    render(){
        return (
            <div className="text-intro" id="site-type">  
                {setInterval(()=>this.sample('igod',1),1000)}
            </div>
        );
    }
}

ReactDOM.render(
  <Sample />,
  document.getElementById('root')
);

相反,我在屏幕上打印了5张.
我如何获得所需的效果?

解决方法:

您可以在您的州中存储计数,并使用间隔每秒递增此计数,并在渲染方法中创建许多舞蹈计数.

class Sample extends React.Component {
  state = { count: 0 };

  componentDidMount() {
    this.interval = setInterval(() => {
      this.setState(previousState => {
        return { count: previousState.count + 1 };
      });
    }, 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return (
      <div className="text-intro" id="site-type">
        {Array.from({ length: this.state.count }, () => <div>Dance</div>)}
      </div>
    );
  }
}

ReactDOM.render(<Sample />, document.getElementById("root"));
<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="root"></div>
上一篇:javascript – Ajax轮询聊天在快速聊天时在消息接收器前端获得重复


下一篇:DevExpress GridView 整理(转)