[英]problem with infinite loop in function hook useEffect
我的鈎子上存在無限循環問題,我正在傳遞本地JSON早餐的數據。 如果您要遍歷地圖數據,那么我將用它來繪制按鈕菜單。 如果在函數末尾刪除數據,並保留空數組,則會向我發送以下錯誤:
const BreakfastComponent = () => {
const breakfast = [
{
id: 0,
name: "Sandwich de jamón y queso",
price: '35',
img: "https://i.ibb.co/ynC9xHZ/sandjc.png",
},
{
id: 1,
name: "Jugo Natural",
price: '15',
img: "https://i.ibb.co/8mrd4MK/orangejuice.png",
},
{
id: 2,
name: "Café americano",
price: '20',
img: "https://i.ibb.co/nsj1GL0/americancoffe.png",
},
{
id: 3,
name: "Café con leche",
price: '28',
img: "https://i.ibb.co/GRPBm7j/coffeandmilk.png",
}
];
const [stateProduct, setStateProduct] = useState([ ]);
useEffect(() => {
setStateProduct(breakfast);
}, [breakfast]);
return (
<section className="databreakfast">
{stateProduct.map((element, item) =>
<ButtonsBComponent
key={item}
{...element}
/>
)}
</section>
)
};
export default BreakfastComponent;
React Hook useEffect缺少依賴項:“ breakfast”。 包括它或刪除依賴項數組react-hooks / exhaustive-deps
useEffect
的第二個參數是要監視的狀態/掛鈎的數組,當狀態/掛鈎更改時,將運行效果。 由於您的breakfast
是const,所以我猜您只想將原始stateProduct
breakfast
。 因此,不要使用[]
作為默認值,而應使用breakfast
。
const [stateProduct, setStateProduct] = useState(breakfast);
另外,在您的react功能組件之外聲明const breakfast ...
可能是一個好主意,這樣它就不會在每次重新渲染時都重新聲明它。
問題很簡單,您將breakfast
數組作為對useEffect
的依賴useEffect
,在useEffect
您要設置Breakfast數組本身。 現在,由於在組件內部聲明了const breakfast數組,因此每次都會生成對其的新引用,並且由於useEffect將數組設置為狀態,因此它會重新渲染,並且在下一次重新呈現時,因為更改了引用,對breakfast
數組的比較將失敗。
解決方案很簡單,您不需要在組件中包含const數組,也不需要使用useEffect
const breakfast = [
{
id: 0,
name: "Sandwich de jamón y queso",
price: '35',
img: "https://i.ibb.co/ynC9xHZ/sandjc.png",
},
{
id: 1,
name: "Jugo Natural",
price: '15',
img: "https://i.ibb.co/8mrd4MK/orangejuice.png",
},
{
id: 2,
name: "Café americano",
price: '20',
img: "https://i.ibb.co/nsj1GL0/americancoffe.png",
},
{
id: 3,
name: "Café con leche",
price: '28',
img: "https://i.ibb.co/GRPBm7j/coffeandmilk.png",
}
];
const BreakfastComponent = () => {
const [stateProduct, setStateProduct] = useState(breakfast);
return (
<section className="databreakfast">
{stateProduct.map((element, item) =>
<ButtonsBComponent
key={item}
{...element}
/>
)}
</section>
)
};
export default BreakfastComponent;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.