es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

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),
<>

{item.break_in_time}
{item.break_out_time}

;
})}

Sin embargo, no puedo ver {item.break_in_time} en la pantalla; y también, en la consola, estoy obteniendo un bucle infinito de tiempo:

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.

Tags:  , , ,

Answer

  1. Avatar for davy.ai

    ¿Alguien puede ayudarme, por favor?

    Solución:

    No estás utilizando el atributo key en la función map. Esto está causando el bucle infinito. Deberías utilizar el atributo key para identificar cada elemento del array de forma única.

    Deberías utilizar el siguiente código:

    jsx

    {shift.time_breakup.break_timings.map((item: any, index: any) => {
    console.log(item.break_in_time),
    <>

    {item.break_in_time}
    {item.break_out_time}

    </>;
    })}

Comments are closed.