使用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:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of 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.
百度了一圈,可能的原因是:
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中