react 如何实现setInterval每过一秒在html中添加一个div ?

react 如何实现setInterval每过一秒在html中添加一个div ?

现在有一个需求是要每过几秒在界面添加一个盒子 之前没写过react
函数应该写在componentDidMount()里面吧
求大佬给个思路~

现在实现了 不知道怎么停下来 我是真滴菜

阅读 5.3k
3 个回答
class App extends Component{
        constructor(props){
            super(props);
            this.state={
                arr:[],
                index:0
            }
            this.handle=null;
            this.stopClickHandle=this.stopClickHandle.bind(this);
        }
        stopClickHandle(){
            if(this.handle){
                clearInterval(this.handle);
                this.handle=null;
            }
        }
        componentDidMount(){
            const me=this;
            this.handle=setInterval(function(){
                me.setState(function(preState){
                    let arr=[preState.index++,...preState.arr];
                    return {arr};
                });
                if(me.state.index == me.props.max){
                    me.stopClickHandle();
                }
            },1000);
        }
        render(){
            let arr=this.state.arr;
            arr=arr.map(function(item){
                return (<div>{item}</div>)
            });
            return(
                <div>
                    {arr}
                </div>
            )
        }
    }
    ReactDOM.render(<App max={5} />,document.body);
import React from "react";
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {arr:["div"]};
  }

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

  componentWillUnmount(){
    clearInterval(this.timeID)
  }

  tick() {
    // 5 个 停止计时器
     if(this.state.arr.length ===5) {
      clearInterval(this.timeID);
      return;
    }
     this.setState((prevState,props) => ({
       arr:[...prevState.arr,props.add]
     }))
  }

  render(){
    return (
      this.state.arr.map((item,idx)=> (
         <div>
            <h1>{item}</h1>
         </div>
      ))
    )
  }
}

ReactDOM.render(
  <Clock add={"div"}/>,
  document.getElementById('root')
);

具体可以看下文档

定时器只定义一次,故一个在初始化阶段定义计时器。
定义在这两个生命周期都可以:
componentWillMount
componentDidMount

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题