2023-03-01 Error: Invalid hook call.Hooks can only be called inside of the body of a function component.
问题描述:rn项目使用钩子useState,详细报错如下:
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.
ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.
ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.
错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一:
1.React和渲染器的版本可能不匹配(例如React DOM)
2.你可能违反了勾手规则
3.同一应用程序中可能有多个React副本
看见https://reactjs.org/link/invalid-hook-call获取有关如何调试和修复此问题的提示。
错误不变冲突:模块AppRegistry不是已注册的可调用模块(调用runApplication)。该错误的常见原因是应用程序条目文件路径不正确。
当JS包损坏或加载React Native时出现早期初始化错误时,也可能发生这种情况。
错误不变冲突:模块AppRegistry不是已注册的可调用模块(调用runApplication)。该错误的常见原因是应用程序条目文件路径不正确。
当JS包损坏或加载React Native时出现早期初始化错误时,也可能发生这种情况。
圈重点:无效的挂钩调用。
原因:我的useState放错地方了。我的代码如下:
import React, { useEffect, useState } from "react"; import { View, Text, SafeAreaView } from "react-native"; const [navList, setNavList] = useState([]); // 看这里,这行代码不应该放在这里,应该放在Home里面 const Home = () => { useEffect(() => { setNavList(['yi', 'er', 'san']); }, []); return ( <SafeAreaView> <View> {navList.map((item, index) => { return ( <View> <Text key={index}>{item}</Text> </View> ) })} </View> </SafeAreaView> ) } export default Home;
正确的写法如下:
import React, { useEffect, useState } from "react"; import { View, Text, SafeAreaView } from "react-native"; const Home = () => { useEffect(() => { setNavList(['yi', 'er', 'san']); }, []); const [navList, setNavList] = useState([]); return ( <SafeAreaView> <View> {navList.map((item, index) => { return ( <View> <Text key={index}>{item}</Text> </View> ) })} </View> </SafeAreaView> ) } export default Home;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧