簡體   English   中英

通過 reducer 更新 state 中的數組

[英]Array update in state via reducer

我正在構建一個測驗應用程序,我想從一系列問題中刪除兩個不正確的答案(如果用戶選擇 50/50 幫助)。 問題是我最終修改了我的原始數組“問題”。 因此,如果用戶再次點擊按鈕播放,並加載第一個問題,它現在只有兩個答案(因為當用戶選擇 50/50 時,這兩個答案被消除了。

我認為克隆數組 let newArrr = [...state.questions] 會解決這個問題,但事實並非如此。 我究竟做錯了什么?

case REMOVE_TWO_INCORRECT_ANSWERS:
  let newArrr = [...state.questions];
  const correctAnswerIndex = state.questions[
    state.currentPage
  ].answers.findIndex((answer) => answer.correct === true);
  let randomNr = Math.ceil(
    Math.random() * state.questions[state.currentPage].answers.length - 1
  );
  if (
    randomNr === correctAnswerIndex &&
    randomNr === state.questions[state.currentPage].answers.length
  ) {
    randomNr--;
  }
  if (randomNr === correctAnswerIndex && randomNr === 0) {
    randomNr++;
  }
  let answers = [
    state.questions[state.currentPage].answers[correctAnswerIndex],
    state.questions[state.currentPage].answers[randomNr],
  ];
  newArrr[state.currentPage].answers = answers;
  return {
    ...state,
    questions: newArrr,
    helpRemoveAnswersUsed: true,
  };

//questions from my local data.js
    case SET_QUESTIONS_SUCCESS:
      return { ...state, loading: false, questions: payload };

newArrr = [...state.questions]確實創建了一個新數組。 問題是數組包含對所有與原始對象相同的對象的引用。 所以當你做newArrr[state.currentPage].answers = answers; ,您在newArrr[state.currentPage]處修改 object,它與原始數組中的 object 相同。

這就是所謂的“淺拷貝”。 要做你想做的事,你需要做一個深拷貝。 換句話說,您還需要克隆每個問題 object...以及它存儲的每個 object...以及這些存儲的對象...等等。 Stack Overflow 上已經有解決方案,其他地方也有如何執行此操作的解決方案。 所以請隨意谷歌它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM