javascript - 减法时在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!'})
}
}
解决方案
我建议这样重组:
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 文档的状态和生命周期部分——它写得很好。
推荐阅读
- ruby-on-rails - 如何使用 Rails 数据库记录 ID 作为 jQuery-UI 的选择器?
- javascript - NPM 模块、ES6、require vs import、共享代码、创建库等
- amazon-ec2 - 如何在 Kubernetes 的 Daemonset 配置文件中使用实例 ID?
- arrays - SAS:使用宏提高数组的效率
- android - Snackbar 的 Android 预发布报告触摸目标大小警告
- java - 如何通过 Selenium Java 将鼠标悬停在具有动态 xpath 的不同图像上
- python - 如何在python中识别维基百科类别
- node.js - 在 res.render() 中指定布局,同时为其提供数据
- python-3.x - 如何通过python从带有条件的pandas数据框中删除第二个连续/出现的重复行?
- assembly - 面对两个函数中的语句?