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

React Native测验APP开发:CheckBox状态管理与用户答案保存问题

报错原因
  • 未初始化对应题目的答案容器:userAnswers初始值为空数组,userAnswers[currentQuestionIndex]对应位置的值为undefined,直接给undefined挂载[key]属性就会触发该类型错误。
  • 违反React状态不可变规范:不能直接修改state的子属性,必须通过setUserAnswers触发状态更新,直接修改原state不会触发组件重渲染,也不符合React的状态管理规则。
等效的setUserAnswers正确写法
function answerClick(value: any, key: any) {
  setUserAnswers(prev => {
    // 拷贝原状态数组,避免修改原始状态
    const newAnswers = [...prev];
    // 若当前题目的答案容器不存在,先初始化为空对象
    if (!newAnswers[currentQuestionIndex]) {
      newAnswers[currentQuestionIndex] = {};
    }
    // 写入当前选项的选中状态
    newAnswers[currentQuestionIndex][key] = value;
    return newAnswers;
  })
}

如果你的多选框支持点击切换选中状态,可根据需求调整赋值逻辑,比如切换布尔值:

newAnswers[currentQuestionIndex][key] = !newAnswers[currentQuestionIndex][key];
需求实现优化方案
  • 如果提前知道总题数,可在初始化状态时直接生成对应长度的空对象数组,避免运行时动态创建容器:假设总题数为totalQuestions,初始化写法如下:
const [userAnswers, setUserAnswers] = useState<Record<number, boolean>[]>(
  Array(totalQuestions).fill({})
);
  • 提交时直接遍历userAnswers数组,按索引和正确答案数组逐题比对,即可统计得分、判定对错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:24:02