简体   繁体   English

使用本机反应从 aws dataStore 查询数据时出现无限循环

[英]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.

相关问题 React Native:使用pop()或goBack()时出现性能问题,导致无限循环。 但是使用`reset`就可以了 - React Native: Performance issue when using `pop()` or `goBack()`, causing an infinite loop. But using `reset` is fine 当显示数组时,React Native post请求会导致无限循环 - React Native post request causes infinite loop when displaying array 使用计数从GAE数据存储区查询 - Querying from GAE datastore using count 如何在 android(java) 中使用 @searchable 在 aws amplify 数据存储中搜索数据? - How to search data in aws amplify datastore using @searchable in android(java)? 在无限循环中不断从数据库中检索数据 - Constantly retrieve data from database in a infinite loop 从 firebase 添加数据会导致无限循环 - Adding data from firebase causes an infinite loop 从本地数据存储区查询时,即使成功固定后,ParseQuery也会提供0个对象 - ParseQuery gives 0 objects when querying from local datastore even after successfully pinning React Native - 无限滚动ListView - React Native - Infinite Scroll ListView 在实现本机Toast模块后使用React Native中的本机模块时未处理的承诺拒绝 - Unhandled promise rejection when using Native Modules from React Native after implementing native Toast module 使用卡片视图从服务器获取本机数据 - React native fetching data from server using card view
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM