Estoy creando una aplicación meteorológica donde tengo una página de índice que muestra un montón de tarjetas para cada hora. Tengo un valor (ya sea AM o PM) que estoy almacenando en una referencia de usuario y pasándolo al componente secundario. Cuando se cumple alguna condición, se llama a una función onChange desde el elemento secundario (esta función existe en el elemento principal) y cambia el valor de la referencia de usuario, pero el valor no cambia en el elemento secundario. El grupo de tarjetas se muestra mediante el mapeo a través de ellas, por lo que espero que si el valor de la referencia de usuario cambia en el padre, la siguiente tarjeta obtendrá el valor modificado, pero esto no está sucediendo. ¿Estoy usando useref mal? índice.js
import type { NextPage } from 'next' import WeatherCard from '../components/WeatherCard' import { motion } from 'framer-motion' import { useEffect, useRef, useState } from 'react' import { PropsType } from '../types' const Home: NextPage<PropsType> = (props) => { const [time,setTime]=useState(new Date()); const timeFormatRef=React.useRef(new Date().toLocaleString('en-US', {hour: 'numeric', hour12: true }).split(' ')[1]) as any; const onTimeFormatChange=()=>{ if(timeFormatRef.current==='AM') timeFormatRef.current='PM' else timeFormatRef.current='AM'; } return ( <div className=> <main> {determineWeatherCardsArr().map((el,index)=>{ return <motion.div> <WeatherCard key={index} weather={el.weather} temp={el.temp} index={index} time={time} ref={timeFormatRef} onTimeFormatChange= {onTimeFormatChange}/> </motion.div>}) </main> </div> ) } export default HomeWeatherCard.js
import Image from "next/image"; const WeatherCard:React.forwardref=(props,ref)=>{ const determineHour=(time:Date):string=>{ let amPmTimeArr=time.toLocaleString('en-US', { hour: 'numeric', hour12: true }).split(' '); let hour [hour]=[...amPmTimeArr] if(+hour+props.index>=12){ hour=(+hour+props.index)%12; if(+hour===0){ props.onTimeFormatChange();//changing the useref here } return hour+ref.current; } else{ hour=+hour+props.index return hour+ref.current; } } let cardTitle=determineHour(props.time) return( <div className=""> <h3 className="">{cardTitle}</h3> </div> ) }React no 'reacciona' a los cambios de valores de referencia, por lo que su componente secundario no se volverá a procesar si cambia el valor de referencia. Use una variable de estado para lograr eso