首页 > 解决方案 > 减法时在reactJS中获取未定义的值

问题描述

我试图获取用户开始输入直到他提交文本的时间间隔。当他点击文本区域时,计时器启动并以秒为单位计算(小时 * 3600 + 分钟 * 60 + 秒)。当他单击提交时,计时器结束也是如此。

现在我的问题是,当我尝试减去保存在 中的两个值时this.state,即使我先将它们存储在 var 中或者如果我执行 a this.setState(),我仍然会得到“未定义”。

    overallTime(e){
        this.setState({Time: this.state.StartTime - this.state.EndTime})
        console.log(this.state.Time)
    }

    onSubmit = (e) => {
        this.overallTime();
        var textinput = this.state.inputValue;
        var inputLength = textinput.length;
        var inputTime = this.state.Time;
        if(textinput === this.state.Content)
        {
            console.log(inputLength)
            var lps = inputLength / inputTime;
            this.setState({LettersPerSecond: lps})
            console.log(lps)
            this.setState({message: 'Your score is ' + this.state.LettersPerSecond + ' letters per second! Good job! Refresh the page for another try!'})
        }
        else
        {
            this.setState({message: 'Your input is incorrect, refresh the page and start again! Remember, you always learn from your failures, so never give up!'})
        }
    }

标签: javascriptreactjs

解决方案


我建议这样重组:

overallTime() {
  return this.state.EndTime - this.state.StartTime;
}

onSubmit = (e) => {
  const totalTime = this.overallTime();

  const textinput = this.state.inputValue;
  const inputLength = textinput.length;
  
  if (textinput === this.state.Content) {
    const lps = inputLength / totalTime;

    this.setState({
      LettersPerSecond: lps,
      message: 'Your score is ' + lps + ' letters per second! Good job! Refresh the page for another try!'
    });
  } else {
    this.setState({
      message: 'Your input is incorrect, refresh the page and start again! Remember, you always learn from your failures, so never give up!'
    })
  }
}

为什么?

setState({Time: someValue});
// this.state.Time doesn't have the new value yet at this point

请参阅 -状态更新可能是异步的。

还有一个小的逻辑错误——你需要做endTime - startTime,而不是startTime - endTime

你的overallTime功能不完全正确——我认为你的意思是这样的:

overallTime() {
  this.setState((state) => ({
    Time: state.EndTime - state.StartTime
  });
}

我强烈建议阅读 React 文档的状态和生命周期部分——它写得很好。


推荐阅读