繁体   English   中英

尝试在 React 的嵌套循环中更改 object 中的值,但我有问题

[英]attempt to change value in object in nested loop in react but i have issue

我有一个反应问题,我有 object 个问题 [{question, correctAnswer, options: [{id, answer, isSelected: false}]}] 我试图在用户选择时将 isSelected 值更改为 true回答 map function 但它只返回一个选项数组而不是整个对象我该怎么做?

这是主要的 object:

主要对象内容

这是我的代码:

    function selectAnswers(id) {
        setQestions(prevQuestions => {
          return prevQuestions.map(question => {
            return question.options.map(answer => {
              return answer.id === id
                ? { ...answer, isSelected: !answer.isSelected }
                : answer;
            });
          });
        });
  }

没有 object 的 rest 的结果:

输入样本

简短的回答,你需要做这样的事情:(我纠正了你的Qestions

function selectAnswers(id) {
  setQuestions((prevQuestions) => {
    return prevQuestions.map((question) => {
      let newQuestion = question;

      question.options.forEach((option, index) => {
        if (option.id === id) {
          const newOption = { ...option, isSelected: !option.isSelected };
          const newOptions = question.options.slice();
          newOptions.splice(index, 1, newOption);
          newQuestion = {
            ...newQuestion,
            options: newOptions,
          };
        }
      });

      return newQuestion;
    });
  });
}

长答案:让我们检查一下您的代码

function selectAnswers(id) {
  setQuestions((prevQuestions) => {
    return prevQuestions.map((question) => {
      return question.options.map((answer) => {
        return answer.id === id
          ? { ...answer, isSelected: !answer.isSelected }
          : answer;
      });
    });
  });
}

您的setQuestions回调应该返回一个新的question数组。 它返回一个数组,让我们看看该数组包含什么。

prevQuestions.map((question) => {
  return question.options.map((answer) => {
    return answer.id === id
      ? { ...answer, isSelected: !answer.isSelected }
      : answer;
  });
});

传递给prevQuestions.map的回调不会返回question object。相反,它会返回一组option (或answer ——为了避免混淆,我建议您只命名您的变量option )。 这就是导致错误的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM