Recibo una respuesta de una API:
{ "data": { // other stuff "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); // saving the response in state // some work } else { Alert.alert('Error', resp); } }) .catch((err: any) => { console.log(err); }); }, []); useEffect(() => { getShiftDetails(); }, [getShiftDetails, ID]); Entonces, he guardado la respuesta en un shift de estado. Ahora quiero mapear este estado para mostrar la hora en la pantalla:
<View> {shift.time_breakup.break_timings.map((item: any, index: any) => { console.log(item.break_in_time), <> <View> <Text>{item.break_in_time}</Text> <Text>{item.break_out_time}</Text> </View> </>; })} </View> Sin embargo, no puedo ver <Text>{item.break_in_time}</Text> en la pantalla; y también, en la consola, obtengo un bucle infinito de tiempo:
consola.log:
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.
ID dentro de la matriz de dependencias getShiftDetails useCallback . const getShiftDetails = useCallback(() => {...}, [ID]) Creo que esto es lo que está causando el ciclo infinito
console.log antes de devolver la vista desde la función de mapa: <View> {shift.time_breakup.break_timings.map((item: any, index: any) => { console.log(item.break_in_time); return ( <View> <Text>{item.break_in_time}</Text> <Text>{item.break_out_time}</Text> </View> ); })} </View>Obtiene un bucle infinito porque en cada procesamiento, su función getShiftDetails se redefine, React crea un objeto poco profundo en cada ciclo de procesamiento, puede usar useCallback para memorizarlo y Declarar ID como matriz de dependencia.