简体   繁体   English

如何在React中使用setInterval?

[英]How to use setInterval with React?

I want the following app to print DAnce every second on the screen. 我希望以下应用程序在屏幕上每秒打印一次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')
);

Instead I get 5 printed on the screen. 相反,我在屏幕上打印了5张。
How do I obtain the desired effect? 我如何获得所需的效果?

You could store a count in your state, and use an interval to increment this count every second and create count many Dance in the render method. 您可以在您的州中存储count ,并使用间隔每秒递增此count并在渲染方法中创建许多Dance count

Example

 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> 

You have to think has the text as something that is changing in your app. 您必须认为文本是应用程序中正在发生变化的内容。 That is ideal for state. 这对国家来说是理想的。

I don't know what your functions sample does. 我不知道你的函数示例是做什么的。 But let's say you have it declared. 但是,让我们说你宣布它。

const sample = (text, i) => { ... };

Then you can do it like this: 然后你可以这样做:

class Sample extends Component {
  state = {
    text: sample('igod', 1),
  };

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        text: this.sample('igod',1)
      });
    }, 1000);
  }

  render() {
    return (
      <div className="text-intro" id="site-type">
        {this.state.text}
      </div>
    );
  }
}

Basically what happens is, when your component mounts you will start a timeout where every 1 second it will update the state thus updating your UI. 基本上发生的情况是,当您的组件安装时,您将开始超时,每1秒钟它将更新状态,从而更新您的UI。

Try this, 试试这个,

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">
         {setTimeout(()=>{this.sample('igod',1)}, 1000)}
         </div>
      );
   }
}
ReactDOM.render(
   <Sample />,
document.getElementById('root')
);

You have used setTimeout which will be called only number of times while component renders. 您已经使用了setTimeout,它将在组件渲染时被调用多次。

You need to use setInterval to work each second. 您需要使用setInterval来每秒工作。

Replace with this. 替换为此。 Hopw this will help you. 随便这会对你有所帮助。

{setInterval(()=>this.sample('igod',1),1000)}

What if you use the react lifecycle : 如果您使用react 生命周期,该怎么办?

 export class Sample extends React.Component { sample(text, i) { this.setState({ text }); } render(){ return( <div className="text-intro" id="site-type"> <h1>{this.state.text}</h1> {setTimeout(()=>this.sample('igod',1),1000)} </div> ); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM