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

218
Views
actualización de la propiedad del objeto de estado: fecha, según el valor anterior

Quiero incrementar la fecha con cada clic de botón (al día siguiente cada clic). ¿Cómo actualizar la propiedad del estado del objeto e incrementar el valor de la fecha correctamente?

 const {useState} = React; const DateComponent = () => { const [date, setDate] = useState({ currDate: new Date().toLocaleDateString(), active: true }); const nextDate = () => { setDate({ ...date, currDate: date.currDate.setDate(date.currDate.getDate() + 1) }); }; return ( <div> <span>{date.currDate}</span> <button onClick={nextDate}>Next Day</button> </div> ); } ReactDOM.createRoot( document.getElementById("root") ).render( <DateComponent /> );
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

Mantenga el estado currDate como un objeto Date y conviértalo en una cadena durante la representación del componente para verlo de la siguiente manera.

Cree un objeto de fecha temporal tempDate para clonar la fecha actual y luego realice la actualización.

 const DateComponent = () => { const [date, setDate] = useState({ currDate: new Date(), active: true, }); const nextDate = () => { setDate(currentData => { const tempDate = new Date(currentData.currDate.getTime()); tempDate.setDate(currentData.currDate.getDate() + 1); return { ...currentData, currDate: tempDate, }; }); }; return ( <div> <span>{date.currDate.toLocaleDateString()}</span> <button onClick={nextDate}>Next Day</button> </div> ); };
about 4 years ago · Santiago Gelvez Report

0

La mejor manera de hacerlo es usando el objeto de vista previa para ese estado cuando usa setDate puede acceder a ese valor en la función, así es como puede usarlo

 const nextDate = () => { setDate(prev => { const newDate = new Date(prev.currDate) newDate.setDate(newDate.getDate() + 1) return { ...prev, currDate: newDate.toLocaleDateString(), }; }); };
about 4 years ago · Santiago Gelvez 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!