小程序从后台获取数据形成弹幕(Taro)

//  页面数据存储
this.state = {
    barrageList_arr: [],
    barrageList_obj: [],
    barrageList: []
    phoneWidth: 0,
}
componentWillMount() {
    const self = this;
    Taro.getSystemInfo({
      success: function (res) {
        console.log('ww',res)
        self.setState({
          phoneWidth: res.windowWidth - 100
        })
      }
    });
}
componentDidMount() {
    setTimeout(() => {
      self.barrageText_move();
      self.barrageListObj();
    },200)
}
  componentWillUnmount() {
    clearInterval(this.timer);
  }
// 从后台获取弹幕数据
ajax.post('请求接口').then(res => {
    // 添加弹幕所需的时间,初始位置
    for (let i = 0; i < res.data.length; i++) {
       res.data[i].width = this.state.phoneWidth;
       res.data[i].time = Math.ceil(Math.random()*10);
       res.data[i].height = Math.ceil(Math.random()*20);
    }
     this.setState({barrageList_arr: res.data})
})
/** 
*因为从后台获取到的是全部的数据,所以要把数据分开,让每条数据有先后之分 
*每隔一秒往barrageList 数组插入一条数据
* */
 barrageListObj() {
    const self = this
    let {barrageList_arr, barrageList_obj} = this.state;
    let i = 0;
    let showTimer = setInterval(function () {
      barrageList_obj.push(barrageList_arr[i]);
      self.setState({barrageList_obj: barrageList_obj, barrageList: barrageList_obj})
      i ++ ;
      if (i > barrageList_arr.length) {
        clearInterval(showTimer)
      }
    },1000)
  }
 /**
   * 定时器,让字幕动起来
   * */
  barrageText_move() {
    const self = this;
    let timerNum = this.state.barrageList_obj;
    for (let i = 0; i < timerNum.length; i ++) {
      setTimeout(function () {
        timerNum.splice(timerNum.indexOf(self), 1);
        self.setState({barrageList: timerNum})
      },timerNum[i].time * 1000)
    }
  }

// 弹幕 HTML
render() {
    let {barrageList} = this.state;
    return(
    
          {barrageList.map((item, i) => {
            return (
              
                
                  {item.XXXX}  // 弹幕内容
                
              
            )
          })}
        
    )
}
.barrage-fly {
    z-index: 3;
    height: 348px;
    width: 100%;
    position: absolute;
    top: 0;
    .barrage-textFly {
      position: absolute;
      white-space:nowrap;
      background-color: #B3503E;
      height: 64px;
      line-height: 64px;
      border-radius: 44px;
      color: #F9C797;
      font-size: 32px;
      padding-right: 30px;
    }
  }
@keyframes first{
  from {left: 100%; }
  to {left: -100%;}
}

你可能感兴趣的:(小程序从后台获取数据形成弹幕(Taro))