Javascript 为什么我收到这个无效的钩子调用错误?
您好,我正在尝试创建一个函数,当您在产品页面上单击“添加到购物车”时将调用该函数。此函数位于单独的文件中,并导入到产品页面,称为onClick。但是,我收到这个错误,它表示调用无效。我做错了什么Javascript 为什么我收到这个无效的钩子调用错误?,javascript,reactjs,Javascript,Reactjs,您好,我正在尝试创建一个函数,当您在产品页面上单击“添加到购物车”时将调用该函数。此函数位于单独的文件中,并导入到产品页面,称为onClick。但是,我收到这个错误,它表示调用无效。我做错了什么 import {AuthContext} from '../context/auth' import gql from 'graphql-tag' import {Button} from 'semantic-ui-react' import {useMutation} from '@apollo/re
import {AuthContext} from '../context/auth'
import gql from 'graphql-tag'
import {Button} from 'semantic-ui-react'
import {useMutation} from '@apollo/react-hooks'
const AddtoCart = (id) => {
console.log(id) //id gets logged into the console here.
const [errors,setErrors] = useState({}) ////shows error right here <<
const {user} = useContext(AuthContext);
const[addtoCart,{loading}] = useMutation(ADDTOCART,{
update(_,result){
//TODO: remove this alert
alert('success')
},
onError(err){
alert('error')
},
variables:{
productID:id
}
})
if(user){
addtoCart(id)
}
else{
if(localStorage.getItem('cart')){
cart = JSON.parse(localStorage.getItem('cart'));
cart.unshift(id);
localStorage.removeItem('cart');
localStorage.setItem('cart', JSON.stringify(cart));
}else{
var cart = [id];
localStorage.setItem('cart', JSON.stringify(cart));
}
}
}
const ADDTOCART = gql`
mutation addtoCart($productID: ID!){
addtoCart(productID: $productID)
}
`
export default AddtoCart;```
从“../context/auth”导入{AuthContext}
从“graphql标记”导入gql
从“语义ui反应”导入{Button}
从“@apollo/react hooks”导入{UseStation}
const AddtoCart=(id)=>{
console.log(id)//id在这里登录到控制台。
const[errors,setErrors]=useState({})///此处显示错误看起来您正在导出AddToCart
并从onClick
调用它?这将不起作用,因为useState
是从错误的上下文调用的。区别在于此函数本身不是React组件。在React组件内部调用该函数component不够,钩子调用需要在自定义钩子(在组件中调用)或组件中发生
如果您希望使用modify state函数,则可以将setErrors
函数作为参数传递给它,并在呈现按钮的组件内部调用useState
。您应该对UseCommutation
和useContext
执行相同的操作
我建议将挂钩提升到包装组件中,然后将user
传递到相关逻辑:
function addToCart(user, id) {
if(user){
addtoCart(id)
}
else {
if(localStorage.getItem('cart')) {
cart = JSON.parse(localStorage.getItem('cart'));
cart.unshift(id);
localStorage.removeItem('cart');
localStorage.setItem('cart', JSON.stringify(cart));
}
else {
var cart = [id];
localStorage.setItem('cart', JSON.stringify(cart));
}
}
}
只要将钩子调用移到容器的范围内,就可以在onClick
中调用此函数
我绝对建议大家阅读一下。这比我解释为什么嵌套函数中不能有钩子做得更好。你导入了React
和useState
?简单地说,你是在破坏。React钩子只在React函数组件和其他自定义钩子中有效,它们也不能在循环中调用,c有条件地,或者在回调中,它显示为一个回调函数