• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

180
Views
¿Por qué mi componente React no se vuelve a renderizar al cambiar de estado con Fecha?

Estoy creando un componente React que permite a un usuario hacer clic en un botón para adelantar la fecha 10 días. Mi código parece actualizar el estado 'selectedDate' pero el componente no se vuelve a procesar. He intentado cambiar el estado a un número (por ejemplo, 500) y hacer que se incremente en + 1 cada vez y eso hace que el componente se vuelva a renderizar. Por alguna razón, no se volverá a representar cuando un estado es un objeto de fecha.

 import React from 'react'; import { useState, useEffect } from 'react'; const BrowserHeader = () => { const today = new Date(); const [selectedDate, setSelectedDate] = useState(today); const onButtonClick = () => { const currentDate = selectedDate; currentDate.setDate(currentDate.getDate()+10); setSelectedDate(currentDate); console.log('selectedDate is now:', selectedDate); }; return ( <div className='browser-header'> <button> <i className="fas fa-fast-backward"></i> </button> <form> <label>Date:</label> <input value={selectedDate} onChange={e => setSelectedDate(e.target.value)} /> <button><i className="fas fa-sync-alt"></i></button> </form> <button onClick={onButtonClick}> <i className="fas fa-fast-forward" ></i> </button> </div> ); }; export default BrowserHeader;
about 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Cambie su controlador onClick como se muestra a continuación. En lugar de actualizar la currentDate . Debe crear una nueva fecha, luego cambiarla y configurarla como el estado actual. De lo contrario, reaccionar ignorará la representación teniendo en cuenta la igualdad referencial.

 const onButtonClick = () => { // create a new date object using prevoius state const newDate = new Date(selectedDate.getDate()); // update it newDate.setDate(selectedDate.getDate() + 10); // set it as the new state setSelectedDate(newDate); };

Al agregar una función de verificación de valor simple a su implementación actual, puede ver que el estado se ha actualizado hasta la fecha antes de 10 días, pero la representación no ha ocurrido => https://codesandbox.io/s/elated-pond-g46mm? archivo=/src/App.js

NOTA: Notará el mismo problema con cualquier estructura de datos mutables como Array , Date , Object , etc.

about 3 years ago · Juan Pablo Isaza Report

0

Leí esto y me di cuenta de dónde iban las cosas mal... ¿Cómo clonar un objeto Date?

Esencialmente, estaba mutando el estado de forma incorrecta cuando dupliqué el objeto de fecha.

about 3 years ago · Juan Pablo Isaza Report

0

Crea un nuevo objeto Fecha a partir de la fecha existente en la que volverá a representar el componente.

 const today = new Date(); const [selectedDate, setSelectedDate] = useState(today); const onButtonClick = () => { const currentDate = new Date(selectedDate); // update here currentDate.setDate(currentDate.getDate() + 10); setSelectedDate(currentDate); console.log("selectedDate is now:", selectedDate); };
about 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error