Invalid hook call 小问题记录

1,159 阅读1分钟

使用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 reactjs.org/link/invali… for tips about how to debug and fix this problem.

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

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

2.代码位置问题 blog.csdn.net/i042416/art…
去官方文档确认了一下,我的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中