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

标签 javascript reactjs react-hooks jsx use-state

我有一个包含问题字段的 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/

相关文章:

reactjs - 如何在 React 中导入子组件?

javascript - "useEffect has a missing dependency"警告有时是错误的吗?

reactjs - 更新 axios post 请求中的全局状态

javascript - 基于 scroll React JS 的 Toggle 类

javascript - 使用基于 html-5 数据属性的 javascript 选择复选框

没有时区的Javascript日期对象

javascript - Window.open() 没有我调用该函数的 url 路径

reactjs - 任务:app:transformNativeLibsWithMergeJniLibsForDebug FAILED

javascript - React Hooks - 设置最后一个值?

javascript - 为什么 JavaScript 不需要 main() 函数?