Invalid hook call 小问题记录

使用useContext出了这么一个bug:

react-dom.development.js:14906 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. 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.

百度了一圈,可能的原因是:

1.有多个react/react-dom版本 https://blog.csdn.net/u011393161/article/details/107807496
通过npm ls react & npm ls react-dom查看,并没有这个情况

2.代码位置问题 https://blog.csdn.net/i042416/article/details/104232565
去官方文档确认了一下,我的createContext没有写错

没有定位到问题,我重新审视了一下自己的代码
发现我的语法是

useEffect(() => {
    const test = useContext(Context)
    console.log(test)
},[])

好像确实有点问题

const test = useContext(Context)
useEffect(() => {
    console.log(test)
},[])

改成这样后,成功了

总结:低端错误,违背了报错的第二条You might be breaking the Rules of Hooks,有些东西不应该写在useEffect中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值