首页 > 解决方案 > 如何强制更新已作为元素文本放入数组的值?

问题描述

我想为从数据库中获得的问题创建一个计时器。用户需要在 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++)它也不起作用

标签: javascriptreactjs

解决方案


因此,在我的情况下,我只需将构造 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>

推荐阅读