[英]React hook Error: Invalid hook call. Hooks can only be called inside of the body of a function component
When I clicked add to cart
button for a individual product then show me error like this:当我单击单个产品的
add to cart
按钮时,会显示如下错误:
Error: Invalid hook call.
错误:无效的挂钩调用。 Hooks can only be called inside of the body of a function component.
钩子只能在 function 组件的主体内部调用。 This could happen for one of the following reasons:
这可能由于以下原因之一而发生:
- You might have mismatching versions of React and the renderer (such as React DOM)
你可能有不匹配的 React 版本和渲染器(例如 React DOM)
- You might be breaking the Rules of Hooks
您可能违反了 Hooks 规则
- You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
您可能在同一个应用程序中拥有多个 React 副本,请参阅https://reactjs.org/link/invalid-hook-call以获取有关如何调试和修复此问题的提示。
I have tried like this: here is my cartScreen.js
code我试过这样:这是我的
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;
But When I have comment out useEffect
hook then does not show me any error:但是当我注释掉
useEffect
钩子时,不会显示任何错误:
useEffect(() => {
if (productId) {
disptach(addToCart(productId, qty));
}
}, [disptach, productId, qty]);
Any suggestion please.请有任何建议。
You need to change this from:您需要将其更改为:
const disptach = useDispatch;
to:至:
const disptach = useDispatch(); // useDispatch() is a hook
Let me know if it works, good Luck让我知道它是否有效,祝你好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.