在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML5  HTML/ react 如何實(shí)現(xiàn)setInterval每過(guò)一秒在html中添加一個(gè)div ?

react 如何實(shí)現(xiàn)setInterval每過(guò)一秒在html中添加一個(gè)div ?

react 如何實(shí)現(xiàn)setInterval每過(guò)一秒在html中添加一個(gè)div ?

現(xiàn)在有一個(gè)需求是要每過(guò)幾秒在界面添加一個(gè)盒子 之前沒(méi)寫(xiě)過(guò)react
函數(shù)應(yīng)該寫(xiě)在componentDidMount()里面吧
求大佬給個(gè)思路~

現(xiàn)在實(shí)現(xiàn)了 不知道怎么停下來(lái) 我是真滴菜

回答
編輯回答
蟲(chóng)児飛

定時(shí)器只定義一次,故一個(gè)在初始化階段定義計(jì)時(shí)器。
定義在這兩個(gè)生命周期都可以:
componentWillMount
componentDidMount

2017年1月9日 14:31
編輯回答
貓館
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);
2018年4月11日 06:27
編輯回答
妖妖
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 個(gè) 停止計(jì)時(shí)器
     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')
);

具體可以看下文檔

2017年3月27日 08:18