Luis Alejandro Nieto Ruth
Luis Fernando Pedroza Taborda
Christian Michael Rosales
Jaime La Rosa
Luis Fernando Pedroza Taborda
Cristian Iñiguez
Víctor Daniel Cardozo Fernández
Vladimir Farrera Vera
Darío Condori Humerez
Matías Daniel Cravero
Ernesto Vladimir Perez Ramos
Juan Manuel Orjuela
Sergio Camilo Castillo Nuñez
Jorge Rodrigo Massón Reynoso
Agustín Navarro Galdon
r2d2bt Barajas Tirado
David Rangel
David Rangel
Ricardo Andres Ardila Enriquez
Ismael Eliezer López Castrejón
Wilmer David Cedeño Mendoza
Deyvid Antonio Arauz Cruz
Daniel Rodríguez
Kenet Andrés Chungandro Montenegro
Jhunior Eduardo Guevara Lázaro
Juan Riquelme
Para navegar entre paginas usamos el siguiente Hook
import { useNavigation } from '@react-navigation/native';
Hacemos una instancia del mismo
const navigation = useNavigation();
Lo usamos para navegar entre paginas Puede recibir dos parametros, el primero el Screen donde queremos ir y el otro los Parametros que le queremos pasar en un objeto de configuracion que es route.params.
navigation.navigate('Pokemon', { id: pokemon.id });
Buen resumen de la clase, gracias.
Podríamos utilizar JSON para pasar el objeto y evitar otra llamada de API pero no se si lo recomiendan para este caso. Por ejemplo:
Convertir el objeto en JSON
navigation.navigate('Pokemon', { pokemon: JSON.stringify(pokemon)});
Convertir el JSON en un objeto de JS
JSON.parse(props.route.params.pokemon)
Si lo datos que necesita son exactamente los mismos no veo por que no, pero seguramente en la pagina de detalles va a querer mostrar mas información del pokemon que la disponible en la lista por lo que tendrá que hacer una llamada a la API en ese caso
Pienso que seria bueno realizarlo, pero como dice el compañero Jaime, se puede necesitar mas informacion del pokemon.
Si hay alguien aqui usando typescript, es necesario indicar los tipos correctos para que no aparezcan errores en el editor:
Primero indicamos los tipos para los parámetros de nuestras pantalla principales en nuestra navegación (en este caso de stack):
// src/navigation/Pokedexnavigation.tsx import React from 'react'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import Pokedex from '../screens/Pokedex'; import Pokemon from '../screens/Pokemon'; // tipando los parametros de cada pantalla principal export type PokedexStackParamList = { Pokedex: undefined; Pokemon: { id: string; }; }; // podemos mandar este tipado a la funcion createStackNavigator (buena practica) const Stack = createNativeStackNavigator<PokedexStackParamList>(); export default function PokedexNavigation() { return (...); }
Luego obtenemos el tipado para el useNavigation, usando el tipado de antes y el genérico NativeStackNavigationProp:
// src/components/PokemonCard.tsx import { FC } from 'react'; import { Image, StyleSheet, Text, TouchableWithoutFeedback, View } from 'react-native'; import { useNavigation } from '@react-navigation/native'; import { capitalize } from 'lodash'; import type { NativeStackNavigationProp } from '@react-navigation/native-stack'; import { getColorByPokemonType } from '../utils/getColorByPokemonType'; import type { PokedexStackParamList } from '../navigation/PokedexNavigation'; type PokemonCardProps = { pokemon: any; }; const PokemonCard: FC<PokemonCardProps> = ({ pokemon }) => { const navigation = useNavigation<NativeStackNavigationProp<PokedexStackParamList>>(); const goToPokemon = () => { navigation.navigate('Pokemon', { id: pokemon.id }); }; ... return (...); }; ... export default PokemonCard;
Muchas gracias por tu aporte !!! Justo me faltaba el paquete de @react-navigation/native-stack y ya con eso pude arreglar el resto de errores de Typescript :D
buen aporte pero tu
type PokemonCardProps = { pokemon: any; };
Lo podrias cambiar por un
export interface TiposDatosPokemon{ id: string, name:string, type: string, order : number, imagen:string, }
yo lo cree en el pokedex donde llamamos los datos de la API y lo exporto para que no tengas que usar any
Yo preferí tener un solo archivo de navegación
#src/navigation/Navigation.js
import React from "react" import { createBottomTabNavigator } from "@react-navigation/bottom-tabs" import { createNativeStackNavigator } from '@react-navigation/native-stack'; import Icon from "react-native-vector-icons/FontAwesome5" import Pokedex from "../screens/Pokedex" import Favorites from "../screens/Favorites" import Account from "../screens/Account" import { Image } from "react-native" import Pokemon from "../screens/Pokemon" export default function Navigation() { const Tab = createBottomTabNavigator() const PokemonStack = createNativeStackNavigator(); const StackPokemon = () => { return (<PokemonStack.Navigator> <PokemonStack.Screen name="Pokedex" component={Pokedex} options={{ title: "Pokemones", headerTransparent: false }} /> <PokemonStack.Screen name="Pokemon" component={Pokemon} /> </PokemonStack.Navigator> ) } return ( <Tab.Navigator> <Tab.Screen name="Favorites" component={Favorites} options={{ tabBarLabel: "Favoritos", headerTitle: "Favoritos", tabBarIcon: ({ color, size }) => <Icon name="heart" color={color} size={size} /> }} /> <Tab.Screen name="StackPokemon" component={StackPokemon} options={{ tabBarLabel: "", headerShown: false, tabBarIcon: () => renderImage() }} /> <Tab.Screen name="Account" component={Account} options={{ tabBarLabel: "Mi cuenta", headerTitle: "Mi cuenta", tabBarIcon: ({ color, size }) => <Icon name="user" color={color} size={size} /> }} /> </Tab.Navigator> ); } function renderImage() { return ( <Image source={require('../assets/pokeball.png')} style={{ width: 65, height: 65, top: -15 }} /> ) }
Genial! me sirvió mucho tu aporte!!
Gracias
Estoy usando la version de react-navigation "^6.1.6"
"@react-navigation/native": "^6.1.6"
En esta version si que puedo enviar todo el objeto con la data del Pokemon
navigation.navigate("Pokemon", { pokemon });
Y la forma en que la recupero es la siguiente:
const { pokemon } = route.params;
a alguien mas se le demora mucho tiempo en renderizar los otros 20 elementos en la aplicacion?
Me sale un mensaje de error tratando de usar el navigation:
The action 'NAVIGATE' with payload was not handled by any navigator.
¿Me puedes mandar una captura del error?
The action 'NAVIGATE' with payload {"name":"Pokemon","params":{"id":5}} was not handled by any navigator.
Do you have a screen named 'Pokemon'?
Algunas cosas cambian para la versión de RN a Julio de 2025. Les dejo mi repo:
Cambia: 1. Como configurar la nueva pestaña de Pokémon. 2. Como mandar y recibir las props por el router.
Para Julio del 2025, para enviar y llamar la info por el router, cambia un poco (tomando en cuenta que en mis apps no uso props genéricas).import { useRouter } from 'expo-router';import { Image, Pressable, StyleSheet, Text, View } from 'react-native';import { useLocalSearchParams } from 'expo-router';import { StyleSheet, Text, View } from 'react-native'; const Pokemon = () => { const params = useLocalSearchParams(); const pokeId = String(params.id); const pokeName = params.name; return ( <View> <Text style={styles.PokemonName}> Estamos en el Pokemon: {pokeName}</Text> <Text style={styles.PokemonId}> El ID del Pokemon: {pokeId}</Text> </View> );}; const styles = StyleSheet.create({ PokemonName: { color: 'white', }, PokemonId: { color: 'white', },}); export default Pokemon; import { capitalize } from '@/utils/capitalize';import { getColourByPokemonType } from '@/utils/getColourByPokemonType';import { PokemonFinalData } from '@/utils/types/PokeTypes'; const PokemonCard: React.FC<PokemonFinalData> = ({ ...PokemonFinalData }) => { const router = useRouter(); const PokemonColour: string = getColourByPokemonType(PokemonFinalData.types); const bgStyles = { backgroundColor: PokemonColour, ...styles.Background }; const goToPokemon = () => { router.push({ pathname: '/pokemon', params: { id: PokemonFinalData.id, name: PokemonFinalData.name, }, }); }; Así se mandan:
import { useRouter } from 'expo-router'; import { Image, Pressable, StyleSheet, Text, View } from 'react-native'; import { capitalize } from '@/utils/capitalize'; import { getColourByPokemonType } from '@/utils/getColourByPokemonType'; import { PokemonFinalData } from '@/utils/types/PokeTypes'; const PokemonCard: React.FC<PokemonFinalData> = ({ ...PokemonFinalData }) => { const router = useRouter(); const PokemonColour: string = getColourByPokemonType(PokemonFinalData.types); const bgStyles = { backgroundColor: PokemonColour, ...styles.Background }; const goToPokemon = () => { router.push({ pathname: '/pokemon', params: { id: PokemonFinalData.id, name: PokemonFinalData.name, }, }); }; ```Así se llaman: ```js import { useLocalSearchParams } from 'expo-router'; import { StyleSheet, Text, View } from 'react-native'; const Pokemon = () => { const params = useLocalSearchParams(); const pokeId = String(params.id); const pokeName = params.name; return ( <View> <Text style={styles.PokemonName}> Estamos en el Pokemon: {pokeName}</Text> <Text style={styles.PokemonId}> El ID del Pokemon: {pokeId}</Text> </View> ); }; const styles = StyleSheet.create({ PokemonName: { color: 'white', }, PokemonId: { color: 'white', }, }); export default Pokemon;
para evitar hacer un nuevo fetch de la informacion del pokemon no se podria convertir el objeto en un string (stringify) para que lo soporte el navigate y luego en la pantalla de pokemon hacer el parse? asi no se evitaria el llamado extra, aunque la verdad no se que seria mas eficiente...
¿Están perdidos algunos videos?
Hay varios que no encuentro y se dificulta comprender algo con la información incompleta :/
A la fecha que estoy escribiendo esto. Noviembre 2023 le pase todo el objeto y no hubo problema pasando todo el objeto pokemon. Estoy usando la version 6
Se me genera este error
Te sugiero revisar el curso #4 ahi se crea el stack de navegación, quizá te ayude a resolver el error.
Tenía el mismo problema, solo verifica que en el PokedexNavigation,js tengas agregado el stack para Pokemon:
Si utilizas react-query y configuras el caché, aún haciendo la petición http se usará la cache y no se hará la peticion de no ser necesario.
Bueno en caso tal de que solo se pueda mandar texto plano en el navigate, creo que algo que se podemos hacer es enviar el objeto como un string (JSON.stringify) y luego parsearlo (JSON.parse)