Soy un principiante de reacción. Quería aleatorizar las opciones con cada carga de página. La opción correcta es el primer elemento de la matriz. El valor de la opción MCQ correcta sigue cambiando. Aunque lo definí antes de la función de matriz shuffle() . ¿Qué estoy haciendo mal?
Versión de reacción: ^ 17.0.2
import React from 'react'; import mcqContent from './mcq-content'; const MCQPage = ({match}) =>{ const reqUrl = match.params.name; const mcqData = mcqContent.find(mcqData => mcqData.m_slug === reqUrl); const correctMcq = mcqData.m_alternatives[0]; const optionsArray = mcqData.m_alternatives const shuffledArray = shuffle(optionsArray) return ( <> <h1>{mcqData.m_title}</h1><br/> <h3>{mcqData.m_question}</h3> {shuffledArray.map((paragraph, key) => ( <p key={key}>{paragraph}</p> ))} <h4>Answer: {correctMcq}</h4> </> ); }; export default MCQPage; function shuffle(array) { let currentIndex = array.length, randomIndex; // While there remain elements to shuffle... while (currentIndex !== 0) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; // And swap it with the current element. [array[currentIndex], array[randomIndex]] = [ array[randomIndex], array[currentIndex]]; } return array; }Cuando pasa una matriz como argumento de función, se pasa como una referencia, lo que significa una referencia a la matriz original. Creo que la solución más segura sería siempre hacer una copia de la matriz original dentro de la función y devolver la matriz recién creada y modificada (por lo que no importa quién esté usando la función, la matriz original nunca cambia).
function shuffle(options) { const array = [...options]; let currentIndex = array.length, randomIndex; // While there remain elements to shuffle... while (currentIndex !== 0) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; // And swap it with the current element. [array[currentIndex], array[randomIndex]] = [ array[randomIndex], array[currentIndex]]; } return array; }