【问题标题】:reactjs, get array in state in for loop?reactjs,在for循环中获取数组状态?
【发布时间】:2017-10-25 08:36:21
【问题描述】:

if 之前的 line console.log 可以记录一个数字,但 if 语句出错 this.state.question[i] 未定义。

4 小时后我不明白为什么?

enter image description here

【问题讨论】:

  • 您可能想要< this.state.question.length 而不是<=。但是为什么你设置你的状态两次,而不是一次呢?

标签: arrays reactjs state


【解决方案1】:

您收到错误是因为您将 question 数组迭代了太多次。如果数组中有 5 个项目,则需要索引 0、1、2、3 和 4。您的循环也会尝试读取索引 5,因为您有:i <= this.state.question.length。请尝试将其更改为 i < this.state.question.length

另外,您设置了两次状态,这是不必要的,并且可能会触发重新渲染超过需要的次数。而是使用临时变量:

handlePlay = (e) => {
  setInterval(function(){
    const time = Math.round(e.target.getCurrentTime());
    let obj = {currentTime: time};  //temporary variable to build your next state
    for(let i = 0;i<=this.state.question.length;i++){
      if(time==this.state.question[i].time){
        obj.currentQuestion = i;  //add stuff to it
      }
    }
    this.setState(obj);  //set your final state here
  }.bind(this),1000)
}

【讨论】:

  • 哦,我犯了一个愚蠢的错误,非常感谢。你拯救了我的一天。 :D
猜你喜欢
  • 1970-01-01
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-13
  • 2017-12-11
  • 1970-01-01
相关资源
最近更新 更多