React应用里Invalid hook call错误消息的处理
【摘要】 今天我做React开发时,遇到如下的错误消息: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 v...
今天我做React开发时,遇到如下的错误消息:
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://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
这个错误输出已经提醒了我,出错误的代码在我的应用程序MyApp.jsx里:
原来是我这段const变量初始化代码写到function外部了:
将其移至内部后错误消失:
假设我要从React的home Component跳转到detail Component.
在home Component里,定义一个点击事件处理函数:
其实现源代码如下:
const history = useHistory();
const handleProgressHeaderClick = () => {
history.push("/detail");
};
测试:点击Progress list后,注意观察url和显示区域的变化:
(1) 从react-router-dom里导入Switch,Route和Redirect组件:
(2) 路径/home指定成加载Home Component ,/detail则加载Detail Component.
文件Home.jsx和Detail.jsx分别实现Component:
(3) 测试:url后加上/home,则加载home Component:
/detail组件的加载:
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)