Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

255
Vistas
React State está cambiando sin usar setState ()

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.

  • Tengo una variable de matriz de estado que llama a allWords . Este estado mantendrá todas las palabras.
  • Y tengo otra variable de matriz de estado que llama como 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é?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda