Tengo un objeto en mi tienda que puedo actualizar cuando se envían acciones. Pero no veo el valor actualizado para totalDevices que se muestra en la página. Se queda con el render original. ¿Qué estoy haciendo mal?
Estado
{ deviceCount: { 'projectId:ed4b4e40-d4e2-4540-8359-c002526f2793': { totalDevices: 1, error: {} }, 'projectId:a6293167-ade2-4e22-98f0-70260fcee7f7': { totalDevices: 0, error: {} } } }Componente
const selectDeviceCount = useSelector((state) => state.deviceCount); const [currDeviceCount, setCurrDeviceCount] = useState(selectDeviceCount); // Using to display value of totalDevices for each item in object useEffect(() => { loadDeviceCountByProjectID({ projectId }); }, [loadDeviceCountByProjectID]); useEffect(() => { // Should this hook trigger a rerender on currDeviceCount? setCurrDeviceCount( selectDeviceCount ); }, [selectDeviceCount]); return ( <ListItem className={variation === 'block' ? classes.listItem : ''} key={projectId} button component={Link} to={`/${organizationName}/${name}?per_page=10&page=1`} > <ListItemText> {name} </span> } /> <ListItemAvatar className={classes.devicesAvatar}> <> <TabletAndroidIcon className={classes.deviceIcon} /> <Typography variant="caption"> // Conditional rendering to prevent errors when state is undefined on first load {selectDeviceCount.length > 0 ? selectDeviceCount[`projectId:${projectId}`]?.totalDevices : 0} </Typography> </> </ListItemAvatar> </ListItem> );Tu uso de ganchos está bien y tu estado debería estar cambiando. Pero está midiendo selectDeviceCount.length en su representación, pero selectDeviceCount es un objeto y, por lo tanto, tiene una longitud de 0. Si desea medir la cantidad de claves dentro del objeto selectDeviceCount , haga Object.keys(selectDeviceCount).length
Para mitigar que selectDeviceCount no esté undefined , simplemente inicialice el estado en un objeto vacío haciendo useState({})
A continuación se muestra el área donde su código tiene el problema.
<Typography variant="caption"> // Conditional rendering to prevent errors when state is undefined on first load {Object.keys(selectDeviceCount).length > 0 ? selectDeviceCount[`projectId:${projectId}`]?.totalDevices : 0} </Typography>