網站搜尋

reactjs - React typescript - 類型必須具有返回迭代器的 '[Symbol.iterator]()' 方法


我這裡有一個示範

https://stackblitz.com/edit/react-ts-shopping-cart-ssofgc?file=Shop.tsx

抱歉,這不是最好的問題,但

我的範例是一個使用 React 和 Typescript 的簡單購物車。

產品可以被加入或從購物車中移除。

我在 stackblitz 的示範可以正常運作,但在我的應用程式中使用相同的程式碼時出現錯誤。

在我的應用程式中,我在 removeFromCart 中遇到錯誤

我在這裡遇到錯誤

const removeFromCart = (
    e: React.MouseEvent<HTMLInputElement, MouseEvent>,
    item: IProduct
  ) => {
    let cartCopy = [...cart]; // Error here - Type 'IProduct' must have a '[Symbol.iterator]()' method that returns an iterator.
    cartCopy = cartCopy.filter(cartItem => cartItem.id !== item.id);
    setCart(cartCopy);
  }; 

錯誤是

Type 'IProduct' must have a '[Symbol.iterator]()' method that returns an iterator.

有人可以解釋這個錯誤或如何修復它嗎?

答案#1

奇怪的是,你在說的地方出現了錯誤,因為你在那一行並沒有使用 item……我本以為你的 cart 類型需要是「類陣列」,也就是說,需要包含 [Symbol.iterator]()。你可以在 MDN 上閱讀更多關於 Symbol.iterator 的資訊。

編輯:我現在在你的 stackblitz 連結中看到,cart 來自 const [cart, setCart]=useState([]);,所以它絕對是一個陣列,因此這不應該是問題。對我來說,似乎是你的編輯器或本地專案配置出了什麼問題...

也許你可以嘗試更明確地指定你的變數類型。例如,items 和 cart 似乎都是 IProduct[],所以你可以將它們改寫成如下形式:

  const [cart, setCart] = useState<IProduct[]>([]);

  const items: IProduct[] = [
    {
      id: 1,
      name: "Product One",
      price: 12
    },
    {
      id: 2,
      name: "Product Two",
      price: 45
    },
    {
      id: 3,
      name: "Product Three",
      price: 23
    }
  ];

答案#2

這可能是由於 tsconfig.json 中的 lib 選項造成的。我更新了一些較新的套件(Redux 7、React 16+),並注意到我的配置嚴重過時。

之前:

tsconfig.json

"target": "es2015",
"lib": [ "dom", "es5", "es2015.symbol", "es2015.core", "es2015.promise" ]

當使用 React.useState 時,這個配置會拋出錯誤。

之後:

tsconfig.json

"target": "es2015",
"lib": [ "dom", "es2015" ]

具體來說,僅添加 es2015.iterable 對這個特定錯誤就足夠了,但在我的情況下沒有理由不添加 es2015。