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;