[英]Error: Invalid hook call. Hooks can only be called inside of the body of a function component. by Routing in react
[英]React hook Error: Invalid hook call. Hooks can only be called inside of the body of a function component
當我單擊單個產品的add to cart
按鈕時,會顯示如下錯誤:
錯誤:無效的掛鈎調用。 鈎子只能在 function 組件的主體內部調用。 這可能由於以下原因之一而發生:
- 你可能有不匹配的 React 版本和渲染器(例如 React DOM)
- 您可能違反了 Hooks 規則
- 您可能在同一個應用程序中擁有多個 React 副本,請參閱https://reactjs.org/link/invalid-hook-call以獲取有關如何調試和修復此問題的提示。
我試過這樣:這是我的cartScreen.js
代碼
import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import { addToCart } from "../action/cartAction";
const CartScreen = (props) => {
const productId = props.match.params.id;
const qty = props.location.search
? Number(props.location.search.split("=")[1])
: 1;
const disptach = useDispatch;
useEffect(() => {
if (productId) {
disptach(addToCart(productId, qty));
}
}, [disptach, productId, qty]);
return (
<div>
<h2>Cart Screen</h2>
<p>
Add to Cart : ProductId: {productId} Qty: {qty}
</p>
</div>
);
};
export default CartScreen;
但是當我注釋掉useEffect
鈎子時,不會顯示任何錯誤:
useEffect(() => {
if (productId) {
disptach(addToCart(productId, qty));
}
}, [disptach, productId, qty]);
請有任何建議。
您需要將其更改為:
const disptach = useDispatch;
至:
const disptach = useDispatch(); // useDispatch() is a hook
讓我知道它是否有效,祝你好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.