Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
React Native: undefined no es un objeto (evaluando 'useContext.getItemsCount')

Soy un principiante en React Native y recibo este error cuando se llama a getItemsCount.

*Haga clic en los enlaces para ver las imágenes

https://i.stack.imgur.com/wbwjZ.png

Este es el código para CartIcon.js:

 import React, {useContext} from 'react'; import {View, Text, StyleSheet} from 'react-native'; import {CartContext} from './CartContext'; export function CartIcon({navigation}){ const {getItemsCount} = useContext(CartContext); return( <View style = {styles.container}> <Text style = {styles.text} onPress = {() => { navigation.navigate('Cart'); }} >Cart ({getItemsCount()}) </Text> </View> ); } const styles = StyleSheet.create({ container: { marginHorizontal: 10, backgroundColor: '#515b8c', height: 40, padding: 15, borderRadius: 38/2, alignItems: 'center', justifyContent: 'center', }, text: { color: '#ccc', fontWeight: 'normal', }, });

https://i.stack.imgur.com/ABYHm.png

Este es el código para CartContext.js:

 import React, {createContext, useState} from 'react'; import {getProduct} from './productService.js'; export const CartContext = createContext(); export function CartProvider(props){ const [items, setItems] = useState([]); function addItemToCart(id){ const product = getProduct(id); setItems((prevItems) => { const item = prevItems.find((item) => (item.id == id)); if(!item){ return [...prevItems, { id, qty: 1, product, totalPrice: product.price }]; } else{ return prevItems.map((item) => { if(item.id == id){ item.qty++; item.totalPrice += product.price; } return item; }); } }); } function getItemsCount(){ return items.reduce((sum,item) => (sum+item.qty),0); } function getTotalPrice(){ return items.reduce((sum,item) => (sum+item.totalPrice),0); } return( <CartContext.Provider value = {{items,setItems,getItemsCount,addItemToCart,getTotalPrice}}> {props.children} </CartContext.Provider> ); }

https://i.stack.imgur.com/HsXoY.png

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

agregue esto a CartContext.js:

 const useCartContext = () => { const context = useContext(CartContext); if (context === undefined) { throw new Error('useCartContext must be used within a CartContextProvider'); } return context; };

y

export { CartProvider, useCartContext };

Vaya a App.jsx y envuelva toda la aplicación con

 <CartProvider> // your app </CartProvider>

Luego, en CartIcon.js importe useCartContext y reemplace

const {getItemsCount} = useContext(CartContext);

con

const { getItemsCount } = useCartContext();

Déjame saber lo que pasa. La idea es crear un enlace, que es mejor, pero el problema aquí es que su componente debe estar dentro de un proveedor para que tenga acceso al contexto.

about 4 years ago · Juan Pablo Isaza Report

0

Adivinando, pero creo que su componente está fuera del proveedor, verifique que su CartIcon esté realmente dentro de CartContext.Provider; de lo contrario, no tendrá acceso a él.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!