React Native类组件中声明const报错:useStore()语法异常排查
问题解决:类组件中使用
useStore导致的语法错误 错误核心原因
你猜的没错,问题出在两点:
- 类组件语法限制:JavaScript类内部只能定义属性、方法,不能直接写
const这类变量声明语句,这是类语法的基础规则,所以会触发unexpected token错误。 - Hooks不能在类组件中用:
useStore是React Redux的Hook,Hook规则明确要求只能在函数组件顶层或自定义Hook里调用,类组件完全不支持Hooks。
修复方案
方案1:直接导入store实例(推荐,改动最小)
如果你的./store文件是直接导出创建好的store实例(比如用configureStore/createStore创建后导出),直接导入即可,不用useStore:
修改导入语句:
// 替换原来的 import { useStore } from "./store"; import store from "./store";
然后删掉类内部的const store = useStore();这一行,剩下代码里的store就能正常使用了。
方案2:转成函数组件(更贴合现代React写法)
如果想改用函数组件+Hooks,重构后的代码示例:
import { StatusBar } from "expo-status-bar"; import { StyleSheet, Text, View } from "react-native"; import { TailwindProvider } from "tailwindcss-react-native"; import { Provider } from "react-redux"; import React, { useState, useEffect } from 'react' import Routes from "./routes"; import { useStore } from "./store"; import Lottie from 'lottie-react-native'; import NetInfo from '@react-native-community/netinfo'; import ButtonCstm from "./custom-components/Button"; // 记得导入colors,不然colors.black会报错 import colors from './path-to-your-colors-file'; export default function Main() { const store = useStore(); const [networkStatus, setNetworkStatus] = useState(""); const checkInternet = async () => { const state = await NetInfo.fetch(); console.log("Connection type", state.type); console.log("Is Connected", state.isConnected); setNetworkStatus(state.isConnected ? "online" : "offline"); }; // 组件加载时检查网络 useEffect(() => { checkInternet(); }, []); if (networkStatus === "online") { return ( <TailwindProvider> <Provider store={store}> <Routes /> <StatusBar style="auto" /> <Text> hey you are online</Text> </Provider> </TailwindProvider> ) } else { return ( <TailwindProvider> <Provider store={store} > <Routes /> <StatusBar style="auto" /> <Lottie style={{ marginBottom: 50, }} source={require('../../assets/animation/no-internet1.json')} autoPlay loop /> <Text style={styles.txt}> hey you are Offline please check your internet</Text> <ButtonCstm stylebtn={{ height: 50, width: 200, backgroundColor: "rgba(90, 154, 230, 1)", borderRadius: 10, position: "absolute", bottom: 80, }} title={"Try Again"} stylebtntitle={{ color: colors.black, fontWeight: "normal", fontSize: 20, marginTop: 12, textAlign: "center", fontFamily: "OpenSans", }} onPress={checkInternet} /> </Provider> </TailwindProvider> ) } } const styles = StyleSheet.create({ txt: { fontSize: 20, fontWeight: "bold", } });
另外注意:代码里的colors.black需要确保已导入或定义,否则会触发新的错误。
内容的提问来源于stack exchange,提问作者Jason0011
相关产品推荐
相关产品推荐

