You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React删除列表元素时意外清除父对象属性的问题求助

问题原因

你在更新目标question时,直接返回了过滤后的answers数组,替换了整个question对象,导致原question的question、number等属性被清除,只剩下answers数组。

解决方案

更新状态时要保留原question的所有属性,仅替换其中的answers字段,修改后的setQuiz逻辑如下:

setQuiz((prev) => ({
  ...prev,
  questions: prev.questions.map((question, x) => {
    if (x === selectedQuestion) {
      // 保留原question的所有属性,只更新answers字段
      return {
        ...question,
        answers: question.answers.filter((element, y) => y !== selectedAnswer)
      };
    }
    return question;
  })
}));
关键说明
  • 用...question复制原question对象的所有属性,避免丢失question、number等非answers字段
  • 仅对answers字段执行过滤替换操作,保证其他属性不受影响
  • 外层的...prev确保quiz对象的title、number等顶级属性也被完整保留

内容的提问来源于stack exchange,提问作者ABpositive

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:27:24