简体   繁体   中英

onClick react error Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop

**I'm getting react Error while trying to change parent component styles onMouseEnter event. How could I change the styles via child component button? The error is - Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. That seems odd for onMouseLeave={() => setHovered(false)} is an arrow function.

https://codesandbox.io/s/trusting-moon-djocul ? **

 // App js import React, { useState, useEffect } from "react"; import Categories from "./Categories"; import ShopPage from "./components/Products"; export default function App() { const [data, setData] = useState(Categories); useEffect(() => { setData(data); }, []); return ( <div className="wrapper"> <ShopPage products={data} filterResult={filterResult} /> </div> ); } // Shopping page const ShopPage = ({ products }) => { return ( <> <div> <Products products={products} /> </div> </> ); }; // Parent component, the main part goes here const Products = ({products}) => { const [hovered, setHovered] = useState(false); const [style, setStyle] = useState(false); if (hovered) { setStyle({ // inline styles }); } else { setStyle({ // inline styles }); } return ( <> <Product setHovered={setHovered} style={style} products={products}/> </> ); }; export default Products; // Child component const Product = ({ setHovered, style, products }) => { return ( <div className={styles.items}> {products.map((value) => { return ( <> <div style={style}> <button onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)} > Add to Cart </button> </div> </> ); })} </div> ); }; export default Product;

The issue is you are setting setHovered state in component, the simple solution could be to use it in useEffect and add required dependency.

If we talk about your code so you can easily do this by using the state in child component instead of passing through props.

I have updated your code below:

https://codesandbox.io/s/nameless-cookies-e6pwxn?file=/src/components/Product.js:141-151

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM