[英]problem when adding item to hooks state react js
我正在嘗試使用hooks
和state
將項目列表存儲在本地存儲中。 但它返回一個錯誤
TypeError
cartList is not iterable
這是我的代碼:(這是代碼 框)
import { useState, useEffect } from "react";
import { Button } from "react-bootstrap";
export default function App() {
const [cartList, setCartList] = useState([]);
const [cartItem, setCartItem] = useState([]);
useEffect(() => {
let localCart = localStorage.getItem("cartList") || "{}";
console.log("localcart", localCart);
if (localCart) {
localCart = JSON.parse(localCart);
}
setCartList(localCart);
}, []);
const handleClick = (e, item) => {
e.preventDefault();
const arr = e.target.id.split("-");
const selectID = arr[1];
console.log("selectID", selectID);
setCartItem({ ...cartItem, id: selectID });
console.log("cartItem", cartItem);
let itemIndex = -1;
for (const entry of Object.entries(cartList)) {
console.log("entry", entry);
}
if (itemIndex < 0) {
setCartList([...cartList, cartItem]); // error occurs here according to codesandbox
localStorage.setItem("cartList", JSON.stringify(cartList));
}
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Button
variant="link"
id="item-12"
onClick={(e) => handleClick(e, cartItem)}
>
item no.12
</Button>
<Button
variant="link"
id="item-100"
onClick={(e) => handleClick(e, cartItem)}
>
item no.100
</Button>
</div>
);
}
我認為您對一種cartList
感到困惑。 我想這將是一個Array
。
const [cartList, setCartList] = useState([]); // It is declared as Array
useEffect(() => {
let localCart = localStorage.getItem("cartList") || "{}"; // But initialized as Object this line
console.log("localcart", localCart);
if (localCart) {
localCart = JSON.parse(localCart);
}
setCartList(localCart);
}, []);
if (itemIndex < 0) {
setCartList([...cartList, cartItem]); // It should be an Array, but error occured as it's an Obejct.
localStorage.setItem("cartList", JSON.stringify(cartList));
}
為什么你得到TypeError: cartList is not iterable
是因為你初始化了cartList
不正確。
請在控制台中嘗試以下代碼段,您將面臨完全相同的錯誤。
console.log( [...{ prop: 'value' }] )
因此,您應該在useEffect
掛鈎中將cartList
初始化為[]
而不是{}
,如下所示。
let localCart = localStorage.getItem("cartList") || "[]";
正如@pilchard 指出的那樣,您將 cartList 設置為該行上的一個對象:
localStorage.getItem("cartList") || "{}";
因此,在將 carlist 值設置為 localstorage 之前的第一次渲染時,您將狀態設置為不能在數組內傳播的對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.