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

如何遍历useState对象数组并修改指定对象?

问题描述

我想要遍历Questions(一个对象列表)并修改符合条件的对象,但代码返回undefined。单独用map打印值是有效的,求正确的修改方法。

现有代码

const [Questions, setQuestions] = React.useState(props.QuestionsData);
const handleClick = (id, isCorrect) => {
  if (isCorrect) {
    setQuestions((prev) => {
      prev.map((item, index) => {
        if (index === id) {
          return {
            ...item,
            [item.Answers.correct.selected]: !item.Answers.correct.selected,
          };
        } else {
          return item;
        }
      });
    });
  } else {
    return;
  }
};

对象结构示例

{
  "category": "Entertainment: Video Games",
  "type": "boolean",
  "difficulty": "hard",
  "question": "The first "Metal Gear" game was released for the PlayStation 1.",
  "correct_answer": "False",
  "incorrect_answers": [
      "True"
  ],
  "Answers": {
      "correct": {
          "MasterId": "MXTOfKnKw7dU7QP0UP0td",
          "id": 0,
          "answer": "False",
          "selected": false,
          "correct": true,
          "userChosen": true
      },
      "wrong": {
          "id": 1,
          "answer": "True",
          "selected": false
      }
  }
}

问题分析与修复

你的代码存在两个核心问题:

  1. setQuestions的回调函数未返回map生成的新数组,导致状态被重置为undefined
  2. 修改嵌套属性的方式错误:用[item.Answers.correct.selected]会把布尔值当作属性名,而非修改Answers.correct.selected本身

修正后的代码:

const [Questions, setQuestions] = React.useState(props.QuestionsData);
const handleClick = (id, isCorrect) => {
  if (!isCorrect) return;

  setQuestions((prev) => 
    prev.map((item, index) => {
      if (index === id) {
        // 逐层解构嵌套对象,仅修改目标属性
        return {
          ...item,
          Answers: {
            ...item.Answers,
            correct: {
              ...item.Answers.correct,
              selected: !item.Answers.correct.selected
            }
          }
        };
      }
      return item;
    })
  );
};

关键说明

  • 必须确保setQuestions的回调返回map生成的新数组,这是React状态更新的要求
  • 修改嵌套对象时,需逐层解构保留原有属性,只更新目标字段,保证状态的不可变性
  • 简化分支逻辑,提前退出无效判断,代码更简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:20:47