Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
React Component no vuelve a renderizar al actualizar un objeto en ganchos de estado

¿Por qué este componente no se actualiza cuando se actualiza el estado? Pero, cuando el archivo se actualiza (como editar y guardar el código), el componente se volverá a representar y mostrará el valor correcto del estado actualizado. Aquí está el código

 import { useReducer } from "react"; import "./styles.css"; const init = [ { name: "Car", stock: 100 }, { name: "Truck", stock: 50 } ]; const reducer = (state, action) => { if (action.type === "add") { state[0].stock++; return state; } else { return state; } }; export default function App() { const [state, dispatch] = useReducer(reducer, init); const addCarStock = () => { dispatch({ type: "add" }); }; return ( <div> <p>Car Stock : {state[0].stock}</p> <button onClick={addCarStock}>Add Car Stock</button> </div> ); }

Puedes abrir este código en sandbox.io

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Cuando haces state[0].stock++; . Cambia la matriz existente (en realidad, puede verificar que la matriz se actualizó colocando un console.log(state); en la primera línea de la función reductora) y cuando reacciona hace una comparación superficial (verificación de referencia) e ignora volver a renderizar asumiendo que es la misma matriz (porque el estado anterior y nuevo se refieren a la misma instancia).

Debe crear una nueva instancia de matriz ( state ) con los cambios y devolverla.

 const reducer = (state, action) => { if (action.type === "add") { return state.map((item,itemIndex) => { if(itemIndex === 0){ return {...item, stock: item.stock + 1} } else { return item; } }); } else { return state; } };

Zona de pruebas de código => https://codesandbox.io/s/recursing-davinci-iid5h?file=/src/App.js

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!