在useEffect中使用自定义Hook触发Invalid hook call错误怎么解决
报错解决方案:Invalid Hook Call
报错本质是违反了React Hook的调用规则:Hook只能在函数组件或自定义Hook的顶层作用域调用,不能嵌套在
useEffect回调、普通函数、条件分支、循环等位置调用。你当前是将自定义Hook的调用写在了useEffect内部,不符合调用规则才抛出异常。
修复方案
你需要实现的「获取Stripe API Key供组件渲染使用」的需求,可直接将相关逻辑封装为自定义Hook,在组件顶层调用即可,示例代码如下:
1. 抽离自定义Hook
import { useState, useEffect } from 'react' import axios from 'axios' // 替换为你项目对应的store、action路径 import store from '@/store' import { loadUser } from '@/actions/userActions' const useStripeApiKey = () => { const [stripeApiKey, setStripeApiKey] = useState('') useEffect(() => { store.dispatch(loadUser()) async function getStripeApiKey() { const { data } = await axios.get('/api/v1/stripeapi') setStripeApiKey(data.stripeApiKey) } getStripeApiKey() }, []) return stripeApiKey }
2. 业务组件内调用
在组件顶层直接调用自定义Hook即可,不要嵌套在任何函数内部:
import { StripeProvider } from '@stripe/react-stripe-js' import { loadStripe } from '@stripe/stripe-js' import useStripeApiKey from './useStripeApiKey' const PayComponent = () => { // 组件顶层调用自定义Hook,符合React规则 const stripeApiKey = useStripeApiKey() const stripePromise = loadStripe(stripeApiKey) return ( <div> {stripeApiKey && ( <StripeProvider stripe={stripePromise}> {/* 你的支付相关业务代码 */} </StripeProvider> )} </div> ) }
如果你的自定义Hook不需要抽离,仅需把原本写在useEffect里的自定义Hook调用,移到组件的最顶层作用域即可,不要放在任何嵌套代码块中。
内容的提问来源于stack exchange,提问作者Tomal Sheikh
相关产品推荐
相关产品推荐

