[英]Infinite loop when querying data from aws dataStore using react native
I am fetching data from AWS DataStore and there is an infinite loop when fetching the cart item data from the DataStore.我正在从 AWS DataStore 获取数据,从 DataStore 获取购物车商品数据时存在无限循环。 I don't know where this loop came from.
我不知道这个循环是从哪里来的。 I tried to wrap fetchCartItems function with useCallback, also removed the dependencies from the useEffect hook but nothing changed.
我试图用 useCallback 包装 fetchCartItems function,还从 useEffect 挂钩中删除了依赖项,但没有任何改变。 I get this infinite loop when I console log the cartProducts.
当我控制台记录购物车产品时,我得到了这个无限循环。
This is the cart item context这是购物车项目上下文
import React, {
useState,
useEffect,
useContext,
createContext,
useCallback,
} from "react";
import { DataStore } from "aws-amplify";
import { CartItems } from "../src/models";
import { useAuthContext } from "./AuthContext";
const CartContext = createContext({});
const CartContextProvider = ({ children }) => {
const [cartProducts, setCartProducts] = useState([]);
const { authUser } = useAuthContext();
const [quantity, setQuantity] = useState("");
// console.log(cartProducts)
const addToCart = async (item) => {
try {
const foundCartItem = await DataStore.query(CartItems, (i) =>
i.productId("eq", item.id)
);
if (foundCartItem.length === 0) {
await DataStore.save(
new CartItems({
userId: authUser.attributes.sub,
productId: item.id,
productPrice: item.price,
productTitle: item.title,
productImage: item.image,
quantity: quantity,
})
);
} else {
return;
}
} catch (error) {
console.log("Error is: ", error);
}
};
const fetchCartItems = async () => {
try {
const cartData = await DataStore.query(CartItems, (user) =>
user.userId("eq", authUser.attributes.sub)
);
setCartProducts(cartData);
} catch (error) {
console.log("Error: ", error);
}
};
useEffect(() => {
fetchCartItems();
}),
[addToCart, quantity];
return (
<CartContext.Provider
value={{
cartProducts,
setCartProducts,
addToCart,
quantity,
setQuantity,
}}
>
{children}
</CartContext.Provider>
);
};
export default CartContextProvider;
export const useCartContext = () => useContext(CartContext);
This is the cart item screen这是购物车项目屏幕
import React from "react";
import {
View,
Text,
Image,
StyleSheet,
FlatList,
TouchableOpacity,
} from "react-native";
import ItemQuantity from "../../component/ItemQuantity";
import Colors from "../../constants/Colors";
import { useCartContext } from "../../contexts/CartContext";
const CartItem = () => {
const { cartProducts } = useCartContext();
return (
<View style={styles.screen}>
<FlatList
data={cartProducts}
renderItem={({ item }) => {
return (
<View style={styles.container}>
<View style={styles.cardView}>
<View style={styles.imageView}>
<Image
style={styles.image}
source={{ uri: item.productImage }}
/>
</View>
<View style={styles.detailsView}>
<Text style={styles.titl}>{item.productTitle}</Text>
<Text style={styles.price}>{item.productPrice} ج.م </Text>
</View>
</View>
<ItemQuantity
updatedItemId={item.id}
quantityItem={item.quantity}
/>
</View>
);
}}
/>
</View>
);
};
const styles = StyleSheet.create({
screen: {
margin: 20,
},
});
The issue here is that you put your useEffect
's dependencies after initialising the hook.这里的问题是您在初始化钩子之后放置了
useEffect
的依赖项。
useEffect(() => {
fetchCartItems();
}),
[addToCart, quantity];
fetchCartItems
is being called with every render, because the hook has no dependencies (not even an empty array making it be called once), and on every call it edits the state, rerendering the dom and calling itself again.每次渲染都会调用
fetchCartItems
,因为该钩子没有依赖项(甚至没有一个空数组使其被调用一次),并且在每次调用时它都会编辑 state,重新渲染 dom 并再次调用自身。
addToCart
shouldn't be in your useEffect
's dependencies, as it as function that you don't ever change in your code. addToCart
不应该在您的useEffect
的依赖项中,因为它是 function ,您永远不会在代码中更改。 Try:尝试:
useEffect(() => {
fetchCartItems();
}, [quantity]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.