Estoy desarrollando un sitio web de cuestionarios/pruebas. Quiero ver diferentes preguntas cuando pase a la siguiente pregunta y no quiero ver las mismas respuestas al mismo tiempo.
allWords . Este estado mantendrá todas las palabras.neverAskedWords . Este estado mantendrá siempre las palabras que nunca usó. Estoy creando una nueva variable de matriz y definiéndola con allWords en una función. Cuando elimino cualquier registro en la nueva variable de matriz, ese registro también se elimina en la variable allWords ... ¿Por qué?
Quiero eliminar cualquier registro en esa matriz temporal y quiero guardar la versión actualizada en el estado neverAskedWords . De esta manera pude ver diferentes preguntas siempre. Aquí están mis códigos.
const [allWords, setAllWords] = useState([]) const [neverAskedWords, setNeverAskedWords] = useState([]) async function getAllData(){ axios .get(`http://127.0.0.1:3000/api/improve-language`) .then(res => { setAllWords(res.data)//defining allWords setNeverAskedWords(res.data)//defining neverAskedWords firstQuestionAndAnswers(res.data)//sending all datas by parameter, bacause when I'm trying to get datas by using `allWords` state, it would be undefined. That's why sending all data by parameter for the first time to set first question and answers. }) .catch(err =>{ console.log(err) }) } async function firstQuestionAndAnswers(wordsList){ let neverAskedList = await wordsList //creating and defining temporary variables const allWordsList = await wordsList //creating and defining temporary variables //some not necessary codes for this issue const questionIndex = randomNumber(neverAskedList.length) const firstQuestion = neverAskedList[questionIndex] let firstAnswers = [] for (let i = 0; i < 4; i++) { let answerIndex = randomNumber(allWordsList.length) firstAnswers[i] = allWordsList[answerIndex] allWordsList.splice(answerIndex, 1)//and here! I'm removing this record to prevent using it again next time, there will be different answers always } //some not necessary codes for this issue firstAnswers.push(firstQuestion) const randomisedAnswers = firstAnswers.sort(()=>Math.random() - 0.5) //some not necessary codes for this issue setQuestion(firstQuestion) setAnswers(randomisedAnswers) //and then here! I'm removing the used question in this time to prevent using it again, there will be different questions always and never see this question again neverAskedList.splice(questionIndex, 1) setNeverAskedWords(neverAskedList) } allWords debería cambiar. Pero cambiando, ¿por qué?
Entonces, lo más obvio que veo en su código es que está modificando el mismo objeto. Lo que debe hacer en su lugar es usar el operador de propagación.
const [allWords, setAllWords] = useState([]) const [neverAskedWords, setNeverAskedWords] = useState([]) async function getAllData(){ axios .get(`http://127.0.0.1:3000/api/improve-language`) .then(res => { setAllWords(res.data)//defining allWords setNeverAskedWords(res.data)//defining neverAskedWords firstQuestionAndAnswers(res.data)//sending all datas by parameter, bacause when I'm trying to get datas by using `allWords` state, it would be undefined. That's why sending all data by parameter for the first time to set first question and answers. }) .catch(err =>{ console.log(err) }) } async function firstQuestionAndAnswers(wordsList){ // don't use await for js objects, should be used only with promises. // use spread operator to make copy of the wordList array so you never actually modify the original object let neverAskedList = [...wordsList] const allWordsList = [...wordsList] //some not necessary codes for this issue const questionIndex = randomNumber(neverAskedList.length) const firstQuestion = neverAskedList[questionIndex] let firstAnswers = [] for (let i = 0; i < 4; i++) { let answerIndex = randomNumber(allWordsList.length) firstAnswers[i] = allWordsList[answerIndex] allWordsList.splice(answerIndex, 1)//and here! I'm removing this record to prevent using it again next time, there will be different answers always } //some not necessary codes for this issue firstAnswers.push(firstQuestion) const randomisedAnswers = firstAnswers.sort(()=>Math.random() - 0.5) //some not necessary codes for this issue setQuestion(firstQuestion) setAnswers(randomisedAnswers) //and then here! I'm removing the used question in this time to prevent using it again, there will be different questions always and never see this question again neverAskedList.splice(questionIndex, 1) setNeverAskedWords(neverAskedList) } Si no entiende por qué sucedió, aquí hay una breve explicación. En js, cuando haces const a = { key: 'val' } , creaste una variable que hace referencia al bloque de memoria que realmente almacena tu objeto. Y cuando haces const b = a estás creando otra variable que hace referencia al mismo bloque de memoria. Entonces, actualizar 1 cambia automáticamente el otro.