gpt4 book ai didi

javascript - useState 变量不是删除函数中的最新版本,React

转载 作者:行者123 更新时间:2023-12-05 03:54:52 24 4
gpt4 key购买 nike

我有一个包含问题字段的 div 列表。对于每个按钮单击,我都会添加一行新的问题字段,并在状态下记住整个列表以及有多少行。我尝试添加一个删除按钮,但是当我的删除功能起作用时,状态变量的值似乎从创建该行时就被记住了。我该如何解决这个问题,以便我可以在 HandleDelete 函数中访问完整列表?

const OefeningAanvragenDagboek = () => {
const { t, i18n } = useTranslation()
const [questionCount, setQuestionCount] = useState(1)
const [questionList, setQuestionList] = useState([])

const createNewLine = () =>{
var newLine=
<div>
<Field type="text" name={"vraag" + questionCount}/>
<Field component="select" name={"antwoordMogelijkheid"+questionCount}>
<option value="">...</option>
<option value="open">{t('oefeningAanvragenDagboek.open')}</option>
<option value="schaal">{t('oefeningAanvragenDagboek.scale')}</option>
</Field>
<Field type="text" name={"type"+questionCount}/>
<button onClick={() => HandleDelete(questionCount-1)}>{t('assignmentCard.delete')}</button>
</div>

setQuestionList(questionList => [...questionList, newLine])
setQuestionCount(questionCount+1)
}

const HandleDelete = (index)=> {
console.log(questionList)
// setQuestionList(questionList.splice(index, 1))

}

return (
<div>
<button onClick={createNewLine}>{t('oefeningAanvragenDagboek.addQuestion')}</button>
{questionList}
</div>
)
}

最佳答案

使用functional setState因为 HandleDelete 已关闭 questionList

setQuestionList(questionList => questionList.splice(index, 1))

Both state and props received by the updater function are guaranteed to be up-to-date.

关于javascript - useState 变量不是删除函数中的最新版本,React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60658489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com