簡體   English   中英

React useState hook 導致無限渲染

[英]React useState hook causes infinite rendering

我根據搜索查詢列出所有產品。 我將列出產品的所有品牌和賣家信息存儲在 useState 掛鈎中。 直到現在它才有效。 現在我想將所有類別存儲在 useState 掛鈎中。

listProducts 是列出的結果版本。 這些結果可以由用戶單獨排序或過濾。 並且 defaultProducts 不會受到影響。 defaultProducts 是我從數據庫中得到的。

  const { query } = useParams();
  const [products, setProducts] = useState([]);
  const [listProducts, setListProducts] = useState([]);
  const [brands, setBrands] = useState([]);
  const [sellers, SetSellers] = useState([]);
  const [Categories, setCategories] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setIsLoading(true);
    
    axios
      .get(`/api/product/search/${query}`)
      .then((res) => res.data)
      .then((data) => {
        setIsLoading(false);
        setProducts(data.products);
        setListProducts(data.products);

        if (data.products.length < 1) {
          setProducts(data.brands);
          setListProducts(data.brands);
        }
      });
  }, [query]);

  useEffect(() => {
    let brandSet = new Set();
    let sellerSet = new Set();
    let categoriesSet = new Set();

    products.forEach((item) => {
      categoriesSet.add(item.category);
      categoriesSet.add(item.subCategory);
      brandSet.add(item.brand);
      sellerSet.add(item.shop.companyName);
    });

    setCategories([...categoriesSet]);
    setBrands([...brandSet]);
    SetSellers([...sellerSet]);
  }, [products]);

最后我渲染ProductFilters組件。

 <ProductFilters
   DefaultProducts={products}
   ListProducts={listProducts}
   Brands={brands}
   Sellers={sellers}
   Categories={Categories}
   setListProducts={setListProducts}
   Brand={brand}
 />

ProductFilters.js

<FilterTypeSection className="mt-3">
        <FilterType>Categories</FilterType>
        <CategoriesSection>
          {Categories.map((categoryItem, index) => {
            return (
              <CategoryItem
                key={index}
                onClick={
                  category === categoryItem
                    ? setCategory("")
                    : setCategory(categoryItem)
                }
                style={
                  categoryItem === category
                    ? { fontWeight: "bold", color: "black" }
                    : { fontWeight: "normal", color: "var(--text-muted)" }
                }
              >
                {categoryItem}
              </CategoryItem>
            );
          })}
        </CategoriesSection>
</FilterTypeSection>

我像上面一樣列出了賣家和品牌數據,他們工作了。 但是當我添加這段代碼時,我得到了這個錯誤:

Unhandled Rejection (Error): Too many re-renders. React limits the number of renders to prevent an infinite loop.
▶ 18 stack frames were collapsed.
(anonymous function)
src/pages/searchResultsPage.js:162
  159 |   sellerSet.add(item.shop.companyName);
  160 | });
  161 | 
> 162 | setCategories([...categoriesSet]);
      | ^  163 | setBrands([...brandSet]);
  164 | SetSellers([...sellerSet]);
  165 | 

即使我為Categories Categories=["a","b","c"]類的 Categories 屬性設置了默認值,我仍然會收到相同的錯誤。

問題

在您的 onClick function 中,您正在執行 function 調用setCategory("") 但是您需要的只是一個 function 簽名,可以在以后用戶單擊它時調用。

所以將您的 onClick 更改為內聯 function。

onClick={() => {
  category === categoryItem
  ? setCategory("")
  : setCategory(categoryItem)
}

如果您不在那里使用箭頭 function,那么setCategory function 將被一次又一次地調用。 您的ProductFilters組件應如下所示:

<FilterTypeSection className="mt-3">
    <FilterType>Categories</FilterType>
    <CategoriesSection>
        {Categories.map((categoryItem, index) => {
            return (
              <CategoryItem
                key={index}
                onClick={
                  () => category === categoryItem
                    ? setCategory("")
                    : setCategory(categoryItem)
                }
                style={
                  categoryItem === category
                    ? { fontWeight: "bold", color: "black" }
                    : { fontWeight: "normal", color: "var(--text-muted)" }
                }
              >
                {categoryItem}
              </CategoryItem>
            );
        })}
    </CategoriesSection>
</FilterTypeSection>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM