javascript - 如何强制更新已作为元素文本放入数组的值?
问题描述
我想为从数据库中获得的问题创建一个计时器。用户需要在 5 分钟内回答。Timer 结构在我放置在单独文件中的 Timer 类中。
<table>
<tr>
<th>ID</th>
<th>Type</th>
<th>Q</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>Timer</th>
</tr>
{this.state.unaccQst}
</table>
<form action="" onSubmit={e => {
e.preventDefault()
...
questionCollector(newForm).then( //get questions from database
data => {
let qstDetArr = []
for(let qstDetails of data){
...
var timer1 = new Timer(5,0) //set a 5 minute timer for each of the questions
var timer2 = setInterval(() => {
let getTime = timer1.getTime() //check the current time
if(getTime.minutes == 0 && getTime.seconds == 0) {
console.log("DELETED")
clearInterval(timer2)
}
else this.setState({[`time_${qstDetails["_id"]}`]: `${getTime.minutes}:${getTime.seconds}`}) //set the current time to a state
console.log(this.state[`time_${qstDetails["_id"]}`]) //this console.log works perfectly (like 4:57, 4:56, 4:55, etc...)
}, 1000)
qstDetArr.push(<tr> //push a table row to an array
<td>{qstDetails["_id"]}</td>
<td>{qstDetails.type}</td>
<td>{qstDetails.translations.en.Q}</td>
<td>{qstDetails.translations.en.A}</td>
<td>{qstDetails.translations.en.B}</td>
<td>{qstDetails.translations.en.C}</td>
<td>{qstDetails.translations.en.D}</td>
<td>{this.state[`time_${qstDetails["_id"]}`]}</td> //this line should update every time the state will update, but it doesn't
</tr>)}
this.setState({unaccQst: [...this.state.unaccQst, ...qstDetArr]})
},
(err) => {}
)
}}>
除了这条线,一切都很好:
<td>{this.state[`time_${qstDetails["_id"]}`]}</td>
哪个值卡住了。这与我将其放入数组时相同。
需要有一种方法来更新它,但即使我想用更礼貌的状态更新它(比如只是 i++)它也不起作用
解决方案
因此,在我的情况下,我只需将构造 tr 所需的数据放入一个状态,然后使用 map() 来完成它:
<table>
<tr>
<th>ID</th>
<th>Type</th>
<th>Q</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>Timer</th>
</tr>
{this.state.unaccQst.map(qst => {
return <tr>
<td>{qst["_id"]}</td>
<td>{qst.type}</td>
<td>{qst.translations.en.Q}</td>
<td>{qst.translations.en.A}</td>
<td>{qst.translations.en.B}</td>
<td>{qst.translations.en.C}</td>
<td>{qst.translations.en.D}</td>
<td>{this.state[`time_${qst["_id"]}`]}</td>
</tr>
})}
</table>
推荐阅读
- scala - 将json转换为scala后如何从json中获取价值?
- php - MySQL计数元素并按日期分组,忽略时间
- python - 为什么python不返回引用?
- fluentd - 使用 fluentd 进行 Rancher 集群日志记录不起作用
- javascript - 从javascript中的字典列表中获取一个数组
- jquery - 使用音频 currentTime 毫秒 Jquery 创建音频步进/节拍查看器
- jquery - jQuery单击图像并“复制/粘贴”将img元素值附加到文本类型的输入中
- intellij-idea - Intellij 2019.1:功能文件中未定义的步骤参考,尽管测试用例工作正常
- prolog - 如何使用 prolog 找到所有路径?
- flutter - 如何从 Stream 返回列表
- 方法?扑