簡體   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