Los datos mapeados no se muestran en la pantalla en React Native.
Estoy recibiendo una respuesta de una API:
{
“data”: {
// otras cosas
“time_breakup”: {
“break_timings”: [
{
“break_in_time”: “2021-11-18T05:32:35.747Z”,
“break_out_time”: “2021-11-18T05:32:47.871Z”
},
{
“break_in_time”: “2021-11-18T06:21:35.740Z”,
“break_out_time”: “2021-11-18T06:21:39.909Z”
}
],
},
},
"success": true
}
Estoy usando la siguiente función para obtener esta respuesta:
const [shift, setShift]: any = useState();
const getShiftDetails = useCallback(() => {
ApiFunctions.get(‘shift/’ + ID)
.then(async resp => {
if (resp) {
setShift(resp.data); // guardando la respuesta en el estado
// algún trabajo
} else {
Alert.alert('Error', resp);
}
})
.catch((err: any) => {
console.log(err);
});
}, []);
useEffect(() => {
getShiftDetails();
}, [getShiftDetails, ID]);
Entonces, he guardado la respuesta en un estado shift. Ahora quiero mapear este estado para mostrar el tiempo en la pantalla:
{shift.time_breakup.break_timings.map((item: any, index: any) => {
console.log(item.break_in_time),
<>
;
})}
Sin embargo, no puedo ver
console.log:
ninguno
2021-11-18T05:32:35.747Z
2021-11-18T06:21:35.740Z
2021-11-18T05:32:35.747Z
2021-11-18T06:21:35.740Z
2021-11-18T05:32:35.747Z
2021-11-18T06:21:35.740Z
2021-11-18T05:32:35.747Z
…
No sé qué estoy haciendo mal.
davy.ai
¿Alguien puede ayudarme, por favor?
Solución:
No estás utilizando el atributo
key
en la funciónmap
. Esto está causando el bucle infinito. Deberías utilizar el atributokey
para identificar cada elemento del array de forma única.Deberías utilizar el siguiente código:
jsx
{item.break_in_time}
{item.break_out_time}
{shift.time_breakup.break_timings.map((item: any, index: any) => {
console.log(item.break_in_time),
<>
</>;
})}